Update only specific fields in MongoDB?


To update only specific field, you can use $set operator. Let us first create a collection with documents

>db.updateOnlySpecificFieldDemo.insertOne({"EmployeeName":"John","EmployeeCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea849d628fa4220163b72")
}
>db.updateOnlySpecificFieldDemo.insertOne({"EmployeeName":"Larry","EmployeeCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea853d628fa4220163b73")
}
>db.updateOnlySpecificFieldDemo.insertOne({"EmployeeName":"David","EmployeeCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea85bd628fa4220163b74")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c9ea849d628fa4220163b72"),
   "EmployeeName" : "John",
   "EmployeeCountryName" : "UK"
}
{
   "_id" : ObjectId("5c9ea853d628fa4220163b73"),
   "EmployeeName" : "Larry",
   "EmployeeCountryName" : "US"
}
{
   "_id" : ObjectId("5c9ea85bd628fa4220163b74"),
   "EmployeeName" : "David",
   "EmployeeCountryName" : "AUS"
}

Following is the query to update only specific field

> db.updateOnlySpecificFieldDemo.update({_id:ObjectId("5c9ea849d628fa4220163b72")},
... {$set: {"EmployeeName":"Robert"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now you can check the field “EmployeeName”:”John” has been updated with value “Robert” or not. Following is the query

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

This will produce the following output

{
   "_id" : ObjectId("5c9ea849d628fa4220163b72"),
   "EmployeeName" : "Robert",
   "EmployeeCountryName" : "UK"
}
{
   "_id" : ObjectId("5c9ea853d628fa4220163b73"),
   "EmployeeName" : "Larry",
   "EmployeeCountryName" : "US"
}
{
   "_id" : ObjectId("5c9ea85bd628fa4220163b74"),
   "EmployeeName" : "David",
   "EmployeeCountryName" : "AUS"
}

Look at the above sample output, “EmployeeName” has been updated successfully.

Updated on: 30-Jul-2019

611 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements