0

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()}})

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly! Could you possibly explain why it is this way and not what I had originally?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.