The $pull operator helps you remove specific items from a list inside your data. It makes cleaning up or updating lists easy without changing the whole list.
$pull operator for removing from arrays in MongoDB
db.collection.updateOne(
{ <filter> },
{ $pull: { <arrayField>: <condition> } }
)$pull removes all array elements that match the <condition>.
The <condition> can be a value or a query expression.
db.users.updateOne(
{ name: "Alice" },
{ $pull: { hobbies: "reading" } }
)db.users.updateOne(
{ name: "Bob" },
{ $pull: { scores: { $lt: 50 } } }
)db.users.updateOne(
{ name: "Carol" },
{ $pull: { tags: { $in: ["old", "expired"] } } }
)This example creates a product with a list of features. Then it removes the feature "bluetooth" from the features array using $pull. It prints the product before and after the update to show the change.
use testdb; // Insert a sample document db.products.insertOne({ name: "Smartphone", features: ["touchscreen", "camera", "bluetooth", "gps"] }); print("Before $pull operation:"); printjson(db.products.findOne({ name: "Smartphone" })); // Remove "bluetooth" feature from the features array const updateResult = db.products.updateOne( { name: "Smartphone" }, { $pull: { features: "bluetooth" } } ); print("Update result:", tojson(updateResult)); print("After $pull operation:"); printjson(db.products.findOne({ name: "Smartphone" }));
Time complexity: Depends on the size of the array; MongoDB scans the array to find matching elements.
Space complexity: Minimal extra space; modifies the document in place.
Common mistake: Using $pull with a condition that matches no elements will not change the array.
Use $pull when you want to remove specific elements from an array without replacing the whole array. Use $set if you want to replace the entire array.
$pull removes matching elements from arrays inside documents.
It works with simple values or query conditions.
It updates only the matching elements, keeping the rest of the array intact.