You can use other operators besides $set
when updating a document.
The $push
operator allows you to push a value into an array, in this case we will add a new nickname to the nicknames
array.
db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}})
// This adds the string 'Tommy' into the nicknames array in Tom's document.
The $pull
operator is the opposite of $push
, you can pull specific items from arrays.
db.people.update({name: 'Tom'}, {$pull: {nicknames: 'Tommy'}})
// This removes the string 'Tommy' from the nicknames array in Tom's document.
The $pop
operator allows you to remove the first or the last value from an array. Let's say Tom's document has a property called siblings that has the value ['Marie', 'Bob', 'Kevin', 'Alex']
.
db.people.update({name: 'Tom'}, {$pop: {siblings: -1}})
// This will remove the first value from the siblings array, which is 'Marie' in this case.
db.people.update({name: 'Tom'}, {$pop: {siblings: 1}})
// This will remove the last value from the siblings array, which is 'Alex' in this case.