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 work with time series data in MongoDB?
- How to use MongoDB queue?
- How to use watch in MongoDB?
- How to check the version of MongoDB?
- How to use triggers in MongoDB?
- How to use unwind in MongoDB?
- How to list MongoDB users?
- What is MongoDB default port?
- How to remove a field from MongoDB?
- How to convert MongoDB ObjectId to string?
See more codes...