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 remove array elements from a document?
Use the $pull operator to remove array elements from a MongoDB document. This operator removes all instances of a value from an existing array field.
Syntax
db.collection.update(
{ },
{ $pull: { fieldName: value } },
{ multi: true }
);
Sample Data
Let us first create a collection with documents −
db.removeArrayElementsDemo.insertMany([
{ "AllPlayerName": ["John", "Sam", "Carol", "David"] },
{ "AllPlayerName": ["Chris", "Robert", "John", "Mike"] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd90d011a844af18acdffc1"),
ObjectId("5cd90d2e1a844af18acdffc2")
]
}
Example: Remove Specific Element
Display all documents to verify the initial data −
db.removeArrayElementsDemo.find().pretty();
{
"_id": ObjectId("5cd90d011a844af18acdffc1"),
"AllPlayerName": [
"John",
"Sam",
"Carol",
"David"
]
}
{
"_id": ObjectId("5cd90d2e1a844af18acdffc2"),
"AllPlayerName": [
"Chris",
"Robert",
"John",
"Mike"
]
}
Remove "John" from all documents −
db.removeArrayElementsDemo.update(
{ },
{ $pull: { AllPlayerName: "John" } },
{ multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })
Verify Result
Check all documents to confirm the removal −
db.removeArrayElementsDemo.find().pretty();
{
"_id": ObjectId("5cd90d011a844af18acdffc1"),
"AllPlayerName": [
"Sam",
"Carol",
"David"
]
}
{
"_id": ObjectId("5cd90d2e1a844af18acdffc2"),
"AllPlayerName": [
"Chris",
"Robert",
"Mike"
]
}
Conclusion
The $pull operator effectively removes all matching elements from array fields across multiple documents when used with multi: true. This provides a clean way to eliminate specific values from arrays in MongoDB collections.
Advertisements
