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
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
-
$pullremoves all instances that match the condition, not just the first occurrence. - Use
multi: trueto apply the operation to multiple documents. - Combine
$pullwith operators like$lt,$gt,$infor 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.
Advertisements
