Update only a single document in MongoDB


To update only a single document in a collection. use updateOne(). Let us first create a collection with documents −

> db.updateOneDemo.insertOne({"StudentId":1,"StudentFirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06ed3725ddae1f53b621e8")
}
> db.updateOneDemo.insertOne({"StudentId":2,"StudentFirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06ed3825ddae1f53b621e9")
}
> db.updateOneDemo.insertOne({"StudentId":1,"StudentFirstName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06ed3825ddae1f53b621ea")
}

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

> db.updateOneDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5e06ed3725ddae1f53b621e8"), "StudentId" : 1, "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5e06ed3825ddae1f53b621e9"), "StudentId" : 2, "StudentFirstName" : "David" }
{ "_id" : ObjectId("5e06ed3825ddae1f53b621ea"), "StudentId" : 1, "StudentFirstName" : "Mike" }

Following is the query to update a single document in MongoDB −

> db.updateOneDemo.updateOne({},{$set:{"StudentFirstName": "Robert"}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Display all documents from a collection with the help of find() method once again since the document is now updated −

> db.updateOneDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5e06ed3725ddae1f53b621e8"), "StudentId" : 1, "StudentFirstName" : "Robert" }
{ "_id" : ObjectId("5e06ed3825ddae1f53b621e9"), "StudentId" : 2, "StudentFirstName" : "David" }
{ "_id" : ObjectId("5e06ed3825ddae1f53b621ea"), "StudentId" : 1, "StudentFirstName" : "Mike" }

Updated on: 31-Mar-2020

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements