Update a single list item of a MongoDB document?


To update a single list item, use positional operator($). 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 }

Following is the query to display all documents from a collection with the help of find() method −

> db.updateASingleListDemo.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "EmployeeName" : "Chris",
   "EmployeeDetails" : [
      {
         "EmployeeId" : "EMP-101",
         "EmployeeSalary" : 18999
      }
   ]
}

Following is the query to update a single list item of a MongoDB document. Here, we are updating the salary −

> db.updateASingleListDemo.update({_id: 1, 'EmployeeDetails.EmployeeId': "EMP-101"}, {$inc: {'EmployeeDetails.$.EmployeeSalary': 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

> db.updateASingleListDemo.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "EmployeeName" : "Chris",
   "EmployeeDetails" : [
      {
         "EmployeeId" : "EMP-101",
         "EmployeeSalary" : 19000
      }
   ]
}
raja
Published on 14-Jun-2019 15:57:54
Advertisements