How to Use $pull Operator in MongoDB: Syntax and Examples
The
$pull operator in MongoDB removes all instances of a specified value or values from an array field in documents. You use it inside an update operation to specify which elements to remove from the array.Syntax
The $pull operator is used inside an update command to remove elements from an array that match a given condition.
It has this basic form:
{ $pull: { <field>: <condition> } }
Where:
- <field> is the name of the array field to modify.
- <condition> is the value or query that matches elements to remove.
mongodb
db.collection.updateMany(
{},
{ $pull: { scores: 50 } }
)Example
This example shows how to remove the number 50 from the scores array in all documents.
It demonstrates removing specific values from an array using $pull.
mongodb
db.students.insertMany([
{ _id: 1, name: "Alice", scores: [80, 50, 90] },
{ _id: 2, name: "Bob", scores: [50, 60, 70] },
{ _id: 3, name: "Charlie", scores: [40, 50, 60] }
])
// Remove all 50s from scores array
const result = db.students.updateMany(
{},
{ $pull: { scores: 50 } }
)
// Find all documents to see the result
const updatedDocs = db.students.find().toArray()
updatedDocsOutput
[
{ _id: 1, name: "Alice", scores: [80, 90] },
{ _id: 2, name: "Bob", scores: [60, 70] },
{ _id: 3, name: "Charlie", scores: [40, 60] }
]
Common Pitfalls
Common mistakes when using $pull include:
- Trying to remove an element that does not exist (no error, but no change).
- Using
$pullon a field that is not an array (no effect). - Confusing
$pullwith$popwhich removes elements by position. - Not using a proper condition for complex queries inside
$pull.
Example of wrong and right usage:
mongodb
// Wrong: Trying to pull a value from a non-array field // Document: { _id: 1, name: "Alice", age: 30 } // This does nothing because 'age' is not an array db.collection.updateOne( { _id: 1 }, { $pull: { age: 30 } } ) // Right: Pull from an array field // Document: { _id: 1, tags: ["red", "blue", "green"] } db.collection.updateOne( { _id: 1 }, { $pull: { tags: "blue" } } )
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $pull | Removes all matching elements from an array | { $pull: { scores: 50 } } |
| $pull with condition | Removes elements matching a query condition | { $pull: { scores: { $lt: 60 } } } |
| $pop | Removes first or last element from an array (not $pull) | { $pop: { scores: -1 } } |
Key Takeaways
Use $pull inside update commands to remove matching elements from arrays.
$pull removes all elements that match the given value or condition.
It only works on array fields; using it on non-arrays has no effect.
Use query conditions inside $pull to remove elements based on criteria.
Remember $pull differs from $pop, which removes elements by position.