MongoDB query to update selected fields


To update selected fields, use UPDATE() in MongoDB. The $set is used to set the new value. Let us create a collection with documents −

> db.demo352.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e55510af8647eb59e5620ba")
}
> db.demo352.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e55510ef8647eb59e5620bb")
}
> db.demo352.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e555112f8647eb59e5620bc")
}
> db.demo352.insertOne({"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e555115f8647eb59e5620bd")
}

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

> db.demo352.find();

This will produce the following output −

{ "_id" : ObjectId("5e55510af8647eb59e5620ba"), "Name" : "Chris" }
{ "_id" : ObjectId("5e55510ef8647eb59e5620bb"), "Name" : "David" }
{ "_id" : ObjectId("5e555112f8647eb59e5620bc"), "Name" : "Bob" }
{ "_id" : ObjectId("5e555115f8647eb59e5620bd"), "Name" : "Mike" }

Following is the query to update selected fields only −

> db.demo352.update({Name:"David"},{$set:{"Name":"Robert"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo352.find();

This will produce the following output −

{ "_id" : ObjectId("5e55510af8647eb59e5620ba"), "Name" : "Chris" }
{ "_id" : ObjectId("5e55510ef8647eb59e5620bb"), "Name" : "Robert" }
{ "_id" : ObjectId("5e555112f8647eb59e5620bc"), "Name" : "Bob" }
{ "_id" : ObjectId("5e555115f8647eb59e5620bd"), "Name" : "Mike" }

Updated on: 02-Apr-2020

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements