totothegreat
totothegreat

Reputation: 1643

Update in mongodb, more than one way?

Im trying to add a "role" to a document, which is an update command such as this:

db.users.update({username: 'someUser'},{'$set': {roles: ['user', 'admin']}});

To a document structured like this:

{
  _id:'22222',
  username : '',
  roles: ['user']
}

Is there any other way of doing this except from the query above?

Upvotes: 0

Views: 35

Answers (1)

zaynetro
zaynetro

Reputation: 2308

There are also $addToSet that adds to set and $pull that removes from set operators.

So your query may look like:

db.users.update(
  { username: 'someUser' },
  { $addToSet: { roles: 'admin' } }
);

UPD: As @Juan Carlos Farah mentioned there is also $push that appends value to array operator.

Upvotes: 3

Related Questions