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 thenamefield of the element in thearrayarray that matches theelementcondition.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to check if array is empty in MongoDB?
- How to join two collections in MongoDB?
- How to specify a password for MongoDB Docker?
- How to check the version of MongoDB?
- How to use unwind in MongoDB?
- How to use MongoDB queue?
- What is MongoDB default port?
- How to perform a health check for MongoDB?
See more codes...