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
Removing an object in a child collection in MongoDB?
To remove an object in a child collection in MongoDB, use the $pull operator combined with the $ positional operator to target the specific nested array and remove matching elements.
Syntax
db.collection.update(
{"parentArray.field": "matchValue"},
{ $pull: { "parentArray.$.childArray": {field: "valueToRemove"} } }
);
Sample Data
db.demo715.insertOne({
_id: 1,
details: [
{
'id': '101',
'Information': [
{
'studentid': '102',
"Name": "Bob"
},
{
'studentid': '103',
"Name": "Chris"
}
]
}
]
});
{ "acknowledged": true, "insertedId": 1 }
Display all documents from the collection ?
db.demo715.find();
{ "_id": 1, "details": [ { "id": "101", "Information": [ { "studentid": "102", "Name": "Bob" }, { "studentid": "103", "Name": "Chris" } ] } ] }
Example: Remove Object from Child Collection
Remove the student with studentid "102" from the Information array ?
db.demo715.update(
{"details.id": '101'},
{ $pull: { 'details.$.Information': {studentid: '102', "Name": "Bob"} } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo715.find();
{ "_id": 1, "details": [ { "id": "101", "Information": [ { "studentid": "103", "Name": "Chris" } ] } ] }
Key Points
- The
$operator matches the first element in the parent array that satisfies the query condition. -
$pullremoves all elements from the nested array that match the specified criteria. - You must specify the complete object to match when using
$pullon object arrays.
Conclusion
Use $pull with the positional operator $ to remove specific objects from nested arrays. The query first identifies the parent array element, then removes matching child objects based on your criteria.
Advertisements
