How to Use $pull in MongoDB: Remove Array Elements Easily
In MongoDB, use the
$pull operator to remove all instances of a specified value or values from an array field in a document. It modifies the array by pulling out matching elements based on a condition or exact value.Syntax
The $pull operator is used inside an update command to remove elements from an array that match a given condition.
{ $pull: { <field>: <condition> } }- removes elements from the array in<field>that match<condition>.<field>is the name of the array field to modify.<condition>can be a value or a query expression to match elements.
mongodb
db.collection.updateOne(
{ <filter> },
{ $pull: { <field>: <condition> } }
)Example
This example shows how to remove the number 3 from the scores array in a document where name is "Alice".
mongodb
db.students.insertOne({ name: "Alice", scores: [1, 3, 5, 3, 7] })
// Remove all 3's from scores array
db.students.updateOne(
{ name: "Alice" },
{ $pull: { scores: 3 } }
)
// Find the updated document
const updatedDoc = db.students.findOne({ name: "Alice" })
updatedDocOutput
{
"_id": ObjectId("..."),
"name": "Alice",
"scores": [1, 5, 7]
}
Common Pitfalls
Common mistakes when using $pull include:
- Using
$pullwithout specifying the correct field name, so no elements are removed. - Trying to pull elements that don't exist, which results in no changes but no error.
- Confusing
$pullwith$pop, which removes elements by position, not by value. - Not using a proper condition for complex objects inside arrays, leading to no matches.
mongodb
/* Wrong: Using $pull without field name */ db.students.updateOne( { name: "Alice" }, { $pull: 3 } // Incorrect syntax ) /* Correct: Specify field and value */ db.students.updateOne( { name: "Alice" }, { $pull: { scores: 3 } } )
Quick Reference
| Operator | Purpose | Example Usage |
|---|---|---|
| $pull | Remove elements from an array matching a condition | { $pull: { scores: 3 } } |
| $pull | Remove objects matching a query | { $pull: { items: { status: "inactive" } } } |
| $pop | Remove first or last element by position | { $pop: { scores: 1 } } |
Key Takeaways
Use $pull to remove all matching elements from an array field in a document.
Specify the array field and the exact value or condition to remove elements correctly.
$pull does not error if no elements match; it simply makes no changes.
Do not confuse $pull with $pop; $pop removes elements by position, $pull by value or condition.
For complex array elements, use query conditions inside $pull to match objects.