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
Update field in exact element array in MongoDB?
To update a specific element in a nested array in MongoDB, use the $ positional operator to match the parent array element, then target the nested array element by its index position using dot notation.
Syntax
db.collection.update(
{"arrayName.field": "matchValue"},
{ $set: { "arrayName.$.nestedArray.INDEX": "newValue" } }
);
Sample Data
Let's create a document with nested arrays to demonstrate the update operation ?
db.updateExactField.insertOne({
"ActorId": 1,
"ActorDetails": [
{
"ActorName": "Johnny Depp",
"MovieList": ["The Tourist", "Public Enemy"]
},
{
"ActorName": "Chris Evans",
"MovieList": ["Captain America", "Avengers"]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("...")
}
Case 1: Update at Index 2 (3rd Position)
Add "Avengers:Infinity War" at index 2 in Chris Evans' MovieList ?
db.updateExactField.update(
{ "ActorDetails.ActorName": "Chris Evans" },
{ $set: { "ActorDetails.$.MovieList.2": "Avengers:Infinity War" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
The updated MovieList for Chris Evans:
"ActorName": "Chris Evans",
"MovieList": [
"Captain America",
"Avengers",
"Avengers:Infinity War"
]
Case 2: Update at Index 1 (2nd Position)
Replace "Avengers" with "Gifted" at index 1 ?
db.updateExactField.update(
{ "ActorDetails.ActorName": "Chris Evans" },
{ $set: { "ActorDetails.$.MovieList.1": "Gifted" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
The final MovieList for Chris Evans:
"ActorName": "Chris Evans",
"MovieList": [
"Captain America",
"Gifted",
"Avengers:Infinity War"
]
Johnny Depp's MovieList remains unchanged because the $ operator only targets the matched element (Chris Evans).
Key Points
-
$matches the first parent array element that satisfies the query condition. - Use dot notation with the numeric index (
.0,.1,.2) to target a specific position in the nested array. - Setting an index beyond the current array length creates the element at that position (sparse array).
- The positional operator works only with the first matched array element in a single update operation.
Conclusion
Combine the $ positional operator with numeric index dot notation (arrayName.$.nestedArray.N) to update exact elements in nested arrays. The $ identifies the matched parent element, and the index targets the specific nested position for precise array manipulation.
