mongodbHow to update an array element in MongoDB?
Updating an array element in MongoDB can be done using the $set
operator. The $set
operator is used to specify the element in an array to update.
Example
db.collection.update(
{ _id: 1 },
{ $set: { "array.$[element].name": "updated" } }
)
Output example
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
The code above updates the name
field of the element in the array
array that matches the element
condition.
Code explanation
db.collection.update
: This is the MongoDB command used to update a document.{ _id: 1 }
: This is the condition used to identify the document to update.{ $set: { "array.$[element].name": "updated" } }
: This is the update operator used to update thename
field of the element in thearray
array that matches theelement
condition.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to update one document in MongoDB?
- How to select specific fields in MongoDB query?
- How to insert new document into MongoDB?
- How to kill an operation in MongoDB?
- How to use hint in MongoDB?
- How to sort MongoDB query results?
- How to implement pagination in MongoDB?
- How to set MongoDB oplog?
- How to rename a field in MongoDB?
See more codes...