1

I have the Collection contexts with documents like the following in my MongoDB (a context has some users with roles)

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

Is there a way to add (or remove) a role to a user with findAndModify.

koalabruder
  • 2,794
  • 9
  • 33
  • 40

1 Answers1

5

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.

Community
  • 1
  • 1
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122