How to Update Nested Array in MongoDB: Syntax and Examples
To update a nested array in MongoDB, use the
$set operator combined with the positional operator ($) to target the specific element inside the array. You can also use array filters with $[identifier] to update multiple nested elements matching a condition.Syntax
The basic syntax to update a nested array element uses the $set operator with the positional $ operator to identify the matched array element. You specify the array field and the position of the element to update.
filter: Finds the document and the nested array element.$set: Updates the nested array element.arrayFilters: Optional, used to update multiple nested elements matching a condition.
mongodb
db.collection.updateOne(
{ "arrayField.nestedField": value },
{ $set: { "arrayField.$.nestedFieldToUpdate": newValue } }
)
// Using arrayFilters for multiple nested elements
db.collection.updateOne(
{ _id: documentId },
{ $set: { "arrayField.$[elem].nestedFieldToUpdate": newValue } },
{ arrayFilters: [ { "elem.nestedField": condition } ] }
)Example
This example updates the score of a specific game inside a nested array of games for a user document. It shows how to find the nested array element by a condition and update its value.
mongodb
db.users.updateOne(
{ "games.name": "chess" },
{ $set: { "games.$.score": 95 } }
)
// Example with arrayFilters to update all games with score less than 50
db.users.updateOne(
{ _id: ObjectId("60d5f483f8d2e30f8c8b4567") },
{ $set: { "games.$[game].score": 60 } },
{ arrayFilters: [ { "game.score": { $lt: 50 } } ] }
)Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
Common mistakes when updating nested arrays include:
- Not using the positional
$operator, which causes the update to fail or update the wrong element. - Forgetting to use
arrayFilterswhen trying to update multiple nested elements. - Using incorrect filter conditions that do not match any nested array element.
Always verify your filter matches the nested element you want to update.
mongodb
/* Wrong: Missing positional operator, updates whole array field */ db.users.updateOne( { "games.name": "chess" }, { $set: { "games.score": 95 } } ) /* Right: Use positional operator to update specific nested element */ db.users.updateOne( { "games.name": "chess" }, { $set: { "games.$.score": 95 } } )
Quick Reference
- $set: Updates the value of a field.
- $: Positional operator to update the first matched element in an array.
- arrayFilters: Filters to update multiple nested elements.
- updateOne(): Updates a single document.
Key Takeaways
Use the positional operator $ to update a specific nested array element.
Use arrayFilters to update multiple nested elements matching a condition.
Always match the nested element correctly in the filter to avoid no updates.
Forgetting to use $ will update the whole array or cause errors.
Test updates on sample data to confirm correct nested array modification.