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()}})
asked Jun 26, 2014 at 20:56

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
answered Jun 26, 2014 at 21:02
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.