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 subdocument from document?
To remove a subdocument from a document in MongoDB, use the $pull operator along with update(). The $pull operator removes all array elements that match a specified condition.
Syntax
db.collection.update(
{ "matchField": "value" },
{ $pull: { "arrayField": { "field": "condition" } } }
);
Create Sample Data
db.demo538.insertOne({
id: 101,
"details": {
anotherDetails: [
{
"Name": "Chris",
Age: 21
},
{
"Name": "David",
Age: 23
},
{
"Name": "Bob",
Age: 20
}
]
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e8c8f0aef4dcbee04fbbc08")
}
Display Original Document
db.demo538.find();
{
"_id": ObjectId("5e8c8f0aef4dcbee04fbbc08"),
"id": 101,
"details": {
"anotherDetails": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "David", "Age": 23 },
{ "Name": "Bob", "Age": 20 }
]
}
}
Remove Subdocument
Remove the subdocument where Age is 23 ?
db.demo538.update(
{ id: 101 },
{ $pull: { "details.anotherDetails": { "Age": 23 } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo538.find();
{
"_id": ObjectId("5e8c8f0aef4dcbee04fbbc08"),
"id": 101,
"details": {
"anotherDetails": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "Bob", "Age": 20 }
]
}
}
Conclusion
Use $pull with update() to remove subdocuments from arrays. The operator removes all elements matching the specified condition, making it effective for cleaning nested array data.
Advertisements
