$push $pull $addToSet
Array operators add, remove and de-duplicate items inside array fields.
In this page:
Syntax
{ $push: { array_field: value } }
{ $addToSet: { array_field: value } }
{ $pull: { array_field: value } }
$push $pull $addToSet
$push appends a value, $addToSet appends only if it is not already present, $pull removes matching elements and $pop removes the first or last. Use $each to add several values at once. All operate in place on the array.
Note:
$addToSet keeps arrays free of duplicates without a read first.
Example: $push $pull $addToSet
test> db.posts.insertOne({ _id: 1, title: "Hello", tags: ["intro"] })
{ acknowledged: true, insertedId: 1 }
test> db.posts.updateOne({ _id: 1 }, { $push: { tags: { $each: ["news", "mongo"] } } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.posts.updateOne({ _id: 1 }, { $addToSet: { tags: "intro" } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 0 }
test> db.posts.updateOne({ _id: 1 }, { $pull: { tags: "news" } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.posts.findOne()
{ _id: 1, title: 'Hello', tags: [ 'intro', 'mongo' ] }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using $set to add one array item
- Expecting $push to avoid duplicates
- Forgetting $each for multiple values
Chapter Summary
- $push appends
- $addToSet appends uniquely
- $pull removes matches
- $each adds several values
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: