0
0
MongoDBquery~5 mins

$pull operator for removing from arrays in MongoDB

Choose your learning style9 modes available
Introduction

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.

You want to remove a specific friend from your list of friends in a user profile.
You need to delete a certain tag from a blog post's tags array.
You want to remove a product from a shopping cart stored as an array.
You want to clear out all completed tasks from a to-do list stored in an array.
Syntax
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.

Examples
Removes the string "reading" from Alice's hobbies array.
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $pull: { hobbies: "reading" } }
)
Removes all scores less than 50 from Bob's scores array.
MongoDB
db.users.updateOne(
  { name: "Bob" },
  { $pull: { scores: { $lt: 50 } } }
)
Removes all tags that are either "old" or "expired" from Carol's tags array.
MongoDB
db.users.updateOne(
  { name: "Carol" },
  { $pull: { tags: { $in: ["old", "expired"] } } }
)
Sample Program

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.

MongoDB
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" }));
OutputSuccess
Important Notes

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.

Summary

$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.