Loading lessons...
Array Update Operators
Array Update Operators
When a document field is an array, MongoDB has dedicated operators to modify it.
The array operators
| Operator | Meaning |
|---|---|
| $push | Adds an element to an array |
| $pull | Removes all elements matching a value |
| $pop | Removes the first or last element |
| $addToSet | Adds an element only if it's not already there |
Using them
// Add "sports" to the tags array
db.posts.updateOne({ title: "Post Title 1" }, { $push: { tags: "sports" } })
// Remove all "events" from tags
db.posts.updateMany({}, { $pull: { tags: "events" } })
// Remove the last element of the tags array
db.posts.updateMany({}, { $pop: { tags: 1 } })
// Add "news" only if it isn't already in tags
db.posts.updateOne({ title: "Post Title 1" }, { $addToSet: { tags: "news" } })
$push vs $addToSet
$pushalways adds the element, even if a duplicate already exists.$addToSetonly adds it if it's not already there (set behavior, no duplicates).
$pop direction
{ $pop: { tags: 1 } } removes the last element; { $pop: { tags: -1 } } removes the first.
TL;DR
$pushappends an element;$addToSetappends only if new.$pullremoves matching elements;$popremoves first or last.