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
Update an array of strings nested within an array of objects in MongoDB
To update an array of strings nested within an array of objects in MongoDB, use the $pull operator with the positional all operator $[] to remove elements from nested arrays across all array elements.
Syntax
db.collection.updateMany(
{ query },
{ $pull: { "arrayField.$[].nestedArray": "valueToRemove" } }
);
Sample Data
db.demo412.insertOne({
"Information1": [
{
"Information2": [
"John",
"David"
]
},
{
"Information2": [
"Mike"
]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e70f38b15dc524f70227683")
}
Display Current Document
db.demo412.find();
{
"_id": ObjectId("5e70f38b15dc524f70227683"),
"Information1": [
{ "Information2": ["John", "David"] },
{ "Information2": ["Mike"] }
]
}
Example: Remove "Mike" from All Nested Arrays
db.demo412.updateMany(
{ _id: ObjectId("5e70f38b15dc524f70227683") },
{ $pull: { 'Information1.$[].Information2': "Mike" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
db.demo412.find();
{
"_id": ObjectId("5e70f38b15dc524f70227683"),
"Information1": [
{ "Information2": ["John", "David"] },
{ "Information2": [] }
]
}
Key Points
-
$[]applies the operation to all elements in the outer array. -
$pullremoves all occurrences of the specified value from arrays. - Use dot notation to access nested arrays within objects.
Conclusion
The $pull operator with $[] effectively removes values from nested string arrays across all objects in the parent array. This approach works when you need to clean up data from multiple nested locations simultaneously.
Advertisements
