MongoDB query to pull / unset with multiple conditions?

To remove array elements that meet multiple conditions in MongoDB, use the $pull operator with query conditions. The $pull operator removes all array elements that match the specified criteria.

Syntax

db.collection.update(
    {matchCriteria},
    { $pull: { "arrayField": {condition} } },
    { multi: true }
);

Sample Data

db.demo198.insertMany([
    {"List": {"Values": [10, 20, 30, 30, 70, 80, 90]}},
    {"List": {"Values": [56, 978, 56, 34, 23, 34]}},
    {"List": {"Values": [21, 12, 14, 15, 34, 56]}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3c224503d395bdc21346df"),
        ObjectId("5e3c225403d395bdc21346e0"),
        ObjectId("5e3c226603d395bdc21346e1")
    ]
}

Display all documents from the collection ?

db.demo198.find();
{ "_id": ObjectId("5e3c224503d395bdc21346df"), "List": { "Values": [ 10, 20, 30, 30, 70, 80, 90 ] } }
{ "_id": ObjectId("5e3c225403d395bdc21346e0"), "List": { "Values": [ 56, 978, 56, 34, 23, 34 ] } }
{ "_id": ObjectId("5e3c226603d395bdc21346e1"), "List": { "Values": [ 21, 12, 14, 15, 34, 56 ] } }

Example: Remove Values Less Than 40

Remove all array elements where the value is less than 40 from all documents ?

db.demo198.update(
    {},
    { "$pull": { "List.Values": { "$lt": 40 } } },
    { "multi": true }
);
WriteResult({ "nMatched": 3, "nUpserted": 0, "nModified": 3 })

Verify Results

db.demo198.find();
{ "_id": ObjectId("5e3c224503d395bdc21346df"), "List": { "Values": [ 70, 80, 90 ] } }
{ "_id": ObjectId("5e3c225403d395bdc21346e0"), "List": { "Values": [ 56, 978, 56 ] } }
{ "_id": ObjectId("5e3c226603d395bdc21346e1"), "List": { "Values": [ 56 ] } }

Key Points

  • $pull removes all instances that match the condition, not just the first occurrence.
  • Use multi: true to apply the operation to multiple documents.
  • Combine $pull with operators like $lt, $gt, $in for complex conditions.

Conclusion

The $pull operator efficiently removes array elements based on multiple conditions. It works across all documents when used with multi: true and supports various query operators for flexible filtering.

Updated on: 2026-03-15T01:42:53+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements