How to Update Array Element in MongoDB: Syntax and Examples
To update an array element in MongoDB, use the
$set operator with the positional operator $ to target the matched element. For example, { $set: { "arrayField.$": newValue } } updates the first matching element in the array.Syntax
Use the updateOne() or updateMany() method with a filter to find the document and the $set operator combined with the positional operator $ to update the matched array element.
filter: Finds the document and array element to update.$set: Sets the new value for the array element.arrayField.$: The$positional operator targets the first matching element in the array.
mongodb
db.collection.updateOne(
{ "arrayField.key": valueToMatch },
{ $set: { "arrayField.$": newValue } }
)Example
This example updates the score of the player named 'Alice' in the players array inside a document.
mongodb
db.games.updateOne(
{ "players.name": "Alice" },
{ $set: { "players.$.score": 95 } }
)Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
Common mistakes include:
- Not using the positional
$operator, which updates the whole array instead of one element. - Using a filter that matches multiple array elements but only the first is updated.
- Trying to update nested fields without specifying the full path.
To update multiple array elements, use arrayFilters introduced in MongoDB 3.6.
mongodb
/* Wrong: updates entire array */ db.games.updateOne( { "players.name": "Alice" }, { $set: { "players": [{ name: "Alice", score: 95 }] } } ) /* Right: updates only matched element */ db.games.updateOne( { "players.name": "Alice" }, { $set: { "players.$.score": 95 } } )
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $set | Sets the value of a field | {"$set": {"field": value}} |
| $ | Positional operator to update matched array element | "arrayField.$" |
| arrayFilters | Filters to update multiple array elements | {"arrayFilters": [{"elem.score": {"$lt": 50}}]} |
Key Takeaways
Use the $set operator with the positional $ operator to update a specific array element.
The filter must match the array element to use the positional operator correctly.
To update multiple elements, use arrayFilters with updateMany or updateOne.
Avoid replacing the entire array when you only want to update one element.
Always specify the full path to nested fields inside the array.