How do I remove elements not matching conditions in MongoDB?

To remove elements not matching conditions in MongoDB, use the $pull operator combined with query conditions. The $pull operator removes all array elements that match the specified condition.

Syntax

db.collection.updateMany(
    { "arrayField": { "$elemMatch": { "field": { "$ne": "value" } } } },
    { "$pull": { "arrayField": { "field": { "$ne": "value" } } } }
);

Sample Data

Let us create a collection with documents ?

db.demo410.insertOne({
    details: [
        {isMarried: false}, 
        {isMarried: true}, 
        {isMarried: false}, 
        {isMarried: "Chris"}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e70efc515dc524f70227681")
}

Display all documents from the collection ?

db.demo410.find();
{
    "_id": ObjectId("5e70efc515dc524f70227681"),
    "details": [
        {"isMarried": false},
        {"isMarried": true},
        {"isMarried": false},
        {"isMarried": "Chris"}
    ]
}

Example: Remove Elements Not Matching Condition

Following query removes all elements where isMarried is not equal to true ?

db.demo410.updateMany(
    {"details": {"$elemMatch": {"isMarried": {"$ne": true}}}},
    {"$pull": {"details": {"isMarried": {"$ne": true}}}}
);
{
    "acknowledged": true,
    "matchedCount": 1,
    "modifiedCount": 1
}

Verify Result

Display the updated document ?

db.demo410.find();
{
    "_id": ObjectId("5e70efc515dc524f70227681"),
    "details": [
        {"isMarried": true}
    ]
}

How It Works

  • $elemMatch identifies documents containing arrays with elements matching the condition
  • $pull removes all array elements where isMarried is not equal to true
  • Elements with values false and "Chris" are removed, keeping only true

Conclusion

Use $pull with $ne to remove array elements not matching specific conditions. The $elemMatch operator helps target documents containing the unwanted elements for efficient removal.

Updated on: 2026-03-15T02:53:38+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements