Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Update a single list item of a MongoDB document?
To update a single list item in MongoDB, use the positional operator ($) to target the first array element that matches your query condition. This operator allows you to update specific fields within array elements without affecting other items in the list.
Syntax
db.collection.update(
{ "arrayField.field": "matchValue" },
{ $set: { "arrayField.$.field": "newValue" } }
);
Sample Data
Let us first create a collection with documents ?
db.updateASingleListDemo.insertOne({
_id: 1,
"EmployeeName": "Chris",
"EmployeeDetails": [
{
"EmployeeId": "EMP-101",
"EmployeeSalary": 18999
}
]
});
{ "acknowledged": true, "insertedId": 1 }
Display all documents from the collection ?
db.updateASingleListDemo.find().pretty();
{
"_id": 1,
"EmployeeName": "Chris",
"EmployeeDetails": [
{
"EmployeeId": "EMP-101",
"EmployeeSalary": 18999
}
]
}
Example: Update Single List Item
Update the salary of employee with ID "EMP-101" by incrementing it by 1 ?
db.updateASingleListDemo.update(
{ _id: 1, 'EmployeeDetails.EmployeeId': "EMP-101" },
{ $inc: { 'EmployeeDetails.$.EmployeeSalary': 1 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Check the updated document ?
db.updateASingleListDemo.find().pretty();
{
"_id": 1,
"EmployeeName": "Chris",
"EmployeeDetails": [
{
"EmployeeId": "EMP-101",
"EmployeeSalary": 19000
}
]
}
Key Points
- The
$positional operator matches the first array element that satisfies the query condition. - Use dot notation to specify the field within the array element to update.
- The query condition must include a field from the array to identify which element to update.
Conclusion
The positional operator $ provides an efficient way to update specific items in MongoDB arrays. It matches array elements based on your query criteria and updates only the targeted fields within those elements.
Advertisements
