- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
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 }
- Related Articles
- Update a MongoDB document with Student Id and Name
- Update only a specific value in a MongoDB document
- In MongoDB how do you use $set to update a nested value/embedded document?
- MongoDB query to update nested document
- Update two separate arrays in a document with one update call in MongoDB?
- How to update the _id of a MongoDB Document?
- How to update a MongoDB document for adding a new item to an array?
- MongoDB findOneAndUpdate() to update a single document
- MongoDB query to update the nested document?
- Display MongoDB with document and subdocument example and update
- How to update an existing document in MongoDB collection using Java?
- Update only a single document in MongoDB
- How to print document value in MongoDB shell?
- How do you update a MongoDB document while replacing the entire document?
- How to update a MongoDB document without overwriting the existing one?

Advertisements