A document in my collection rooms
has the following structure:
{
"_id": { "$oid": "4edaaa4a8d285b9311eb63ab" },
"users": [
{
"userId": { "$oid": "4edaaa4a8d285b9311eb63a9" },
"unreadMessages": 0
},
{
"userId": { "$oid": "4edaaa4a8d285b9311eb63aa" },
"unreadMessages": 0
},
]
}
I'd like to increment unreadMessages
of the second user (the one at index 1 in the array), if I know the ObjectId
of the first user. Knowing the _id
of the document is sufficient for selecting, but for updating I need to be able to reference to the other user, so I'm also selecting by users
. I'm doing so with the following update call:
collections.rooms.update(
{
_id: ObjectId("4edaaa4a8d285b9311eb63ab"),
users: { // not first user
$elemMatch: { $ne: { userId: ObjectId("4edaaa4a8d285b9311eb63a9") } }
}
},
{
// this should increment second user's unreadMessages,
// but does so for unreadMessages of first user
$inc: { "users.$.unreadMessages": 1 }
}
);
It increments unreadMessages
of the first user, not of the second user. I guess this is because $ne
actually matches on the first user, and apparently that's what users.$
is referring to.
How should I modify this call so that the second user's unreadMessages
is incremented?