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
How to find and modify a value in a nested array?
To find and modify a value in a nested array, use the $elemMatch operator to locate the array element and the $ positional operator with $set to update the specific field value.
Syntax
db.collection.update(
{ arrayName: { $elemMatch: { field: "matchValue" } } },
{ $set: { "arrayName.$.targetField": "newValue" } }
);
Sample Data
db.findAndModifyAValueInNestedArrayDemo.insertOne({
"CompanyName": "Amazon",
"DeveloperDetails": [
{
"ProjectName": "Online Book Store",
"TeamSize": "5"
},
{
"ProjectName": "Library Management System",
"TeamSize": "7"
},
{
"ProjectName": "Online Banking Application",
"TeamSize": "15"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ca275226304881c5ce84b9f")
}
Example: Update TeamSize in Nested Array
Let's modify the TeamSize to 20 for the project "Online Banking Application" ?
db.findAndModifyAValueInNestedArrayDemo.update(
{ DeveloperDetails: { $elemMatch: { ProjectName: "Online Banking Application" } } },
{ $set: { "DeveloperDetails.$.TeamSize": "20" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.findAndModifyAValueInNestedArrayDemo.find().pretty();
{
"_id": ObjectId("5ca275226304881c5ce84b9f"),
"CompanyName": "Amazon",
"DeveloperDetails": [
{
"ProjectName": "Online Book Store",
"TeamSize": "5"
},
{
"ProjectName": "Library Management System",
"TeamSize": "7"
},
{
"ProjectName": "Online Banking Application",
"TeamSize": "20"
}
]
}
Key Points
-
$elemMatchmatches the first array element that satisfies the query condition -
$positional operator references the matched array element for updates - Use dot notation with
$to target specific fields within the matched element
Conclusion
The combination of $elemMatch and $ positional operator provides an efficient way to find and modify specific values in nested arrays. This approach updates only the first matching element in the array.
Advertisements
