Update a MongoDB document with Student Id and Name


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

> db.demo427.insertOne({"StudentId":101,"StudentName":"Chris Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75e711bbc41e36cc3cae75")
}
> db.demo427.insertOne({"StudentId":102,"StudentName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75e71abbc41e36cc3cae76")
}
> db.demo427.insertOne({"StudentId":103,"StudentName":"John Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75e725bbc41e36cc3cae77")
}
> db.demo427.insertOne({"StudentId":104,"StudentName":"Carol Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e75e733bbc41e36cc3cae78")
}

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

> db.demo427.find();

This will produce the following output −

{ "_id" : ObjectId("5e75e711bbc41e36cc3cae75"), "StudentId" : 101, "StudentName" : "Chris Brown" }
{ "_id" : ObjectId("5e75e71abbc41e36cc3cae76"), "StudentId" : 102, "StudentName" : "David Miller" }
{ "_id" : ObjectId("5e75e725bbc41e36cc3cae77"), "StudentId" : 103, "StudentName" : "John Smith" }
{ "_id" : ObjectId("5e75e733bbc41e36cc3cae78"), "StudentId" : 104, "StudentName" : "Carol Taylor" }

Following is the query to update MongoDB document −

> db.demo427.update({"StudentId":102},{$set:{"StudentName":"John Doe"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo427.find();

This will produce the following output −

{ "_id" : ObjectId("5e75e711bbc41e36cc3cae75"), "StudentId" : 101, "StudentName" : "Chris Brown" }
{ "_id" : ObjectId("5e75e71abbc41e36cc3cae76"), "StudentId" : 102, "StudentName" : "John Doe" }
{ "_id" : ObjectId("5e75e725bbc41e36cc3cae77"), "StudentId" : 103, "StudentName" : "John Smith" }
{ "_id" : ObjectId("5e75e733bbc41e36cc3cae78"), "StudentId" : 104, "StudentName" : "Carol Taylor" }

Updated on: 03-Apr-2020

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements