← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 4 of 7

$push $pull $addToSet

Array operators add, remove and de-duplicate items inside array fields.

In this page:

  1. $push $pull $addToSet
Syntax
javascript
{ $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

bash
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
  1. Using $set to add one array item
  2. Expecting $push to avoid duplicates
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.