MongoDB query to update a specific document from a collection


To update, use $set along with UPDATE. Let us create a collection with documents −

>db.demo135.insertOne({"Details":[{"EmployeeId":101,"EmployeeName":"Chris","EmployeeSalary":45000},{"EmployeeId":102,"EmployeeName":"Chris","EmployeeSalary":45000}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31a5ddfdf09dd6d085399c")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e31a5ddfdf09dd6d085399c"),
   "Details" : [
      {
         "EmployeeId" : 101,
         "EmployeeName" : "Chris",
         "EmployeeSalary" : 45000
      },
      {
         "EmployeeId" : 102,
         "EmployeeName" : "Chris",
         "EmployeeSalary" : 45000
      }
   ]
}

Following is the query to update second document −

> db.demo135.update(
...    {
...
...       "Details.EmployeeId":102,
...
...    },
...    {
...       $set: {
...          "Details.$.EmployeeName" : "John Doe"
...       }
...    }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e31a5ddfdf09dd6d085399c"),
   "Details" : [
      {
         "EmployeeId" : 101,
         "EmployeeName" : "Chris",
         "EmployeeSalary" : 45000
      },
      {
         "EmployeeId" : 102,
         "EmployeeName" : "John Doe",
         "EmployeeSalary" : 45000
      }
   ]
}

Updated on: 31-Mar-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements