MongoDB query to pull multiple values from array

To pull multiple values from an array across multiple documents in MongoDB, use the $pull operator with the multi: true option. This removes matching array elements from all documents that meet the query criteria.

Syntax

db.collection.update(
    { queryCondition },
    { $pull: { arrayField: { matchCondition } } },
    { multi: true }
);

Sample Data

db.demo392.insertMany([
    {
        Name: "Chris",
        details: [
            { _id: "101" },
            { _id: "102" }
        ]
    },
    {
        Name: "Chris",
        details: [
            { _id: "104" },
            { _id: "101" }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e5d2b3322064be7ab44e802"),
        ObjectId("5e5d2b3422064be7ab44e803")
    ]
}

Verify Initial Data

db.demo392.find();
{
    "_id": ObjectId("5e5d2b3322064be7ab44e802"), 
    "Name": "Chris", 
    "details": [
        { "_id": "101" }, 
        { "_id": "102" }
    ]
}
{
    "_id": ObjectId("5e5d2b3422064be7ab44e803"), 
    "Name": "Chris", 
    "details": [
        { "_id": "104" }, 
        { "_id": "101" }
    ]
}

Example: Pull Values from Multiple Documents

Remove all array elements with _id: "101" from all documents ?

db.demo392.update(
    { },
    { $pull: { details: { _id: "101" } } },
    { multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })

Verify Result

db.demo392.find();
{ "_id": ObjectId("5e5d2b3322064be7ab44e802"), "Name": "Chris", "details": [ { "_id": "102" } ] }
{ "_id": ObjectId("5e5d2b3422064be7ab44e803"), "Name": "Chris", "details": [ { "_id": "104" } ] }

Key Points

  • multi: true ensures the operation affects all matching documents, not just the first one.
  • $pull removes all occurrences of matching elements from each array.
  • Empty query { } matches all documents in the collection.

Conclusion

Use $pull with multi: true to remove matching array elements from multiple documents simultaneously. This approach is efficient for bulk array modifications across your entire collection.

Updated on: 2026-03-15T02:47:26+05:30

594 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements