Can I use something like findAndModify on a deep nested document with MongoDB? -


i have collection contexts documents following in mongodb (a context has users roles)

{     "__v" : 0,     "_id" : objectid("53dea71a713d636e1fea705a"),     "name" : "team4",     "users" : [          {             "userid" : "53a347467f311d7c1731f91b",             "roles" : [                  "admin"             ]         },          {             "userid" : "536d2e8be0f9697e13b95c87",             "roles" : []         }     ] } 

is there way add (or remove) role user findandmodify.

yes, it's possible. can using both update , findandmodify commands.

to add role user call:

db.contexts.update({   _id: objectid('53dea71a713d636e1fea705a'),   'users.userid': '536d2e8be0f9697e13b95c87' }, {   $push: {     'users.$.roles': 'admin'   } }) 

to remove role user call:

db.contexts.update({   _id: objectid('53dea71a713d636e1fea705a'),   'users.userid': '53a347467f311d7c1731f91b' }, {   $pull: {     'users.$.roles': 'admin'   } }) 

note i'm using positional operator $ specify exact user subdocument update.

here example of using findandmodify same task:

db.contexts.findandmodify({   query: {     _id: objectid('53dea71a713d636e1fea705a'),     'users.userid': '536d2e8be0f9697e13b95c87'   },   update: {     $push: {       'users.$.roles': 'admin'     }   },   new: true }) 

the real difference between update , findandmodify commands findandmodify returns modified document, while update returns operation status.

findandmodify operation equivalent of calling both find , update operations, except findandmodify performs both operations in single transaction. more information see this question.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -