Yes, it's possible. You can do it using both update and findAndModify commands.
To add role to a user call:
db.contexts.update({
_id: ObjectId('53dea71a713d636e1fea705a'),
'users.userId': '536d2e8be0f9697e13b95c87'
}, {
$push: {
'users.$.roles': 'admin'
}
})
To remove role from a user call:
db.contexts.update({
_id: ObjectId('53dea71a713d636e1fea705a'),
'users.userId': '53a347467f311d7c1731f91b'
}, {
$pull: {
'users.$.roles': 'admin'
}
})
Note that I'm using positional operator $
to specify an exact user
subdocument to
update.
Here is an example of using findAndModify
for the same task:
db.contexts.findAndModify({
query: {
_id: ObjectId('53dea71a713d636e1fea705a'),
'users.userId': '536d2e8be0f9697e13b95c87'
},
update: {
$push: {
'users.$.roles': 'admin'
}
},
new: true
})
The only real difference between update
and findAndModify
commands is that findAndModify
returns you a modified document, while update
only returns operation status.
findAndModify
operation is an equivalent of calling both find
and update
operations, except that findAndModify
performs both operations in a single transaction. For more information see this question.