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
Deleting specific record from an array nested within another array in MongoDB
To delete specific record from an array nested within another array in MongoDB, use the $pull operator combined with the $ positional operator to target the correct parent array element and remove the matching nested document.
Syntax
db.collection.update(
{ "parentArray.field": "matchValue" },
{ $pull: { "parentArray.$.nestedArray": { "field": "valueToDelete" } } }
);
Sample Data
db.demo213.insertOne({
"id": 101,
"details1": [
{
"Name": "Chris",
"details2": [
{
"StudentName": "David",
"Subject": "MongoDB"
},
{
"StudentName": "Mike",
"Subject": "MySQL"
}
]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e3e300c03d395bdc2134704")
}
Example: Delete Record from Nested Array
Remove the student record with Subject "MySQL" from the nested details2 array ?
db.demo213.update(
{ "id": 101, "details1.Name": "Chris" },
{ $pull: { "details1.$.details2": { "Subject": "MySQL" } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo213.find().pretty();
{
"_id": ObjectId("5e3e300c03d395bdc2134704"),
"id": 101,
"details1": [
{
"Name": "Chris",
"details2": [
{
"StudentName": "David",
"Subject": "MongoDB"
}
]
}
]
}
Key Points
- The
$positional operator identifies the first matching parent array element. -
$pullremoves all documents from the nested array that match the specified condition. - Multiple nested records can be deleted if they match the same criteria.
Conclusion
Use $pull with the $ positional operator to delete specific records from nested arrays. This approach allows precise targeting of nested documents while preserving the overall document structure.
Advertisements
