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
Pull an element in sub of sub-array in MongoDB?
To pull an element from a sub-array within a nested array in MongoDB, use $pull combined with the $ positional operator. This allows you to target and remove specific elements from deeply nested array structures.
Syntax
db.collection.update(
{ "parentArray.field": "matchValue" },
{ $pull: { "parentArray.$.subArray": { "field": "valueToRemove" } } }
);
Create Sample Data
db.demo679.insertOne({
id: 1,
"details": [
{
CountryName: "US",
"information": [
{ "Name": "Chris", "FirstName": "Name=Chris" },
{ "Name": "Bob", "FirstName": "Name=Bob" }
]
},
{
CountryName: "UK",
"information": [
{ "Name": "Robert", "FirstName": "Name=Robert" },
{ "Name": "Sam", "FirstName": "Name=Sam" }
]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea442cf04263e90dac943fd")
}
Example: Remove Element from Nested Array
Remove Bob's record from the US country's information array ?
db.demo679.update(
{ "details.CountryName": "US" },
{ $pull: { "details.$.information": { "Name": "Bob", "FirstName": "Name=Bob" } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo679.find().pretty();
{
"_id": ObjectId("5ea442cf04263e90dac943fd"),
"id": 1,
"details": [
{
"CountryName": "US",
"information": [
{
"Name": "Chris",
"FirstName": "Name=Chris"
}
]
},
{
"CountryName": "UK",
"information": [
{
"Name": "Robert",
"FirstName": "Name=Robert"
},
{
"Name": "Sam",
"FirstName": "Name=Sam"
}
]
}
]
}
How It Works
- The query
{"details.CountryName": "US"}matches the parent array element -
$identifies the matched array element (US country record) -
$pullremoves the specified object from theinformationsub-array
Conclusion
Use $pull with the $ positional operator to remove elements from nested arrays. The $ targets the matched parent element, while $pull removes the specified sub-array element that matches all provided field-value pairs.
Advertisements
