Update Document with Marks Value in MongoDB for Student David



Use forEach() and traverse to find student name David update new marks for the same student. Let us create a collection with documents −

> db.demo634.insertOne({Name:"Chris","Marks":76});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c0ea66c954c74be91e6c9")
}
> db.demo634.insertOne({Name:"Bob","Marks":67});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c0ead6c954c74be91e6ca")
}
> db.demo634.insertOne({Name:"David","Marks":37});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c0eb76c954c74be91e6cb")
}

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

> db.demo634.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c0ea66c954c74be91e6c9"), "Name" : "Chris", "Marks" : 76 }
{ "_id" : ObjectId("5e9c0ead6c954c74be91e6ca"), "Name" : "Bob", "Marks" : 67 }
{ "_id" : ObjectId("5e9c0eb76c954c74be91e6cb"), "Name" : "David", "Marks" : 37 }

Following is the query to update document with marks value of student David −

> db.demo634.find({Name:"David"}).forEach(function(d){ db.demo634.update({_id:d._id},{$set:{Marks:98}}); })

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

> db.demo634.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c0ea66c954c74be91e6c9"), "Name" : "Chris", "Marks" : 76 }
{ "_id" : ObjectId("5e9c0ead6c954c74be91e6ca"), "Name" : "Bob", "Marks" : 67 }
{ "_id" : ObjectId("5e9c0eb76c954c74be91e6cb"), "Name" : "David", "Marks" : 98 }
Updated on: 2020-05-12T07:45:25+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements