Scalahansolo
Scalahansolo

Reputation: 3065

MongoDB update attribute nested array

I currently have a database that is structured as followed...

"_id" : "neRmMTTkRvoKFGL3a",
"active_users" : [
            {
                    "user" : {
                            "_id" : "CYyxPcAnfhns28stb",
                            ...
                    },
                    "last_seen" : 1403814568360
            },
            {
                Other users....
            }
],
"room_name": "TestRoom"

I want to be able to update the last_seen attribute. I have been trying to use the following query (or variations of it) but have had no luck so far. Any help would be much appreciated.

db.rooms.update({room_name: "TestRoom",
                'active_users.user._id': 'CYyxPcAnfhns28stb'
                }, {$set: {'active_users.last_seen.$': Date.now()}})

Upvotes: 0

Views: 64

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42073

The positional operator ($) is at the wrong place. This code should work:

db.rooms.update({room_name: "TestRoom",
                'active_users.user._id': 'CYyxPcAnfhns28stb'
                }, {$set: {'active_users.$.last_seen': Date.now()}})

The positional operator identifies an element in array. In your case active_users is the array. If you know the position of the element, you can use its index:

'active_users.1'
      ^       ^
    array   index

This references the first element in the array:

{
        "user" : {
                "_id" : "CYyxPcAnfhns28stb",
                ...
        },
        "last_seen" : 1403814568360
}

If you don't know the index, you need to use the positional operator $:

'active_users.$'
      ^       ^
    array   index

This positional operator references the element in the array which was matched in the query ('active_users.user._id': 'CYyxPcAnfhns28stb').

Then in the update query you want to update the last_seen field. So it becomes:

'active_users.$.last_seen'
      ^       ^     ^
    array   index field

Upvotes: 2

Related Questions