How to update document with marks value in MongoDB for student David

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 12-May-2020 07:45:02
Advertisements