Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$elemMatchidentifies documents containing arrays with elements matching the condition -
$pullremoves all array elements whereisMarriedis not equal totrue - Elements with values
falseand"Chris"are removed, keeping onlytrue
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.
Advertisements
