- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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 }Advertisements