Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to update document with marks value in MongoDB for student David
To update a specific document's marks value for student David in MongoDB, you can use the forEach() method to traverse the collection and find the student, then update their marks using the $set operator.
Syntax
db.collection.find({Name: "StudentName"}).forEach(function(doc) {
db.collection.update({_id: doc._id}, {$set: {Marks: newValue}});
});
Sample Data
Let us create a collection with student documents ?
db.demo634.insertMany([
{Name: "Chris", Marks: 76},
{Name: "Bob", Marks: 67},
{Name: "David", Marks: 37}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e9c0ea66c954c74be91e6c9"),
ObjectId("5e9c0ead6c954c74be91e6ca"),
ObjectId("5e9c0eb76c954c74be91e6cb")
]
}
Display all documents from the collection ?
db.demo634.find();
{ "_id" : ObjectId("5e9c0ea66c954c74be91e6c9"), "Name" : "Chris", "Marks" : 76 }
{ "_id" : ObjectId("5e9c0ead6c954c74be91e6ca"), "Name" : "Bob", "Marks" : 67 }
{ "_id" : ObjectId("5e9c0eb76c954c74be91e6cb"), "Name" : "David", "Marks" : 37 }
Example: Update David's Marks Using forEach()
Update David's marks from 37 to 98 using forEach() traversal ?
db.demo634.find({Name: "David"}).forEach(function(d) {
db.demo634.update({_id: d._id}, {$set: {Marks: 98}});
});
Verify Result
Display all documents to confirm the update ?
db.demo634.find();
{ "_id" : ObjectId("5e9c0ea66c954c74be91e6c9"), "Name" : "Chris", "Marks" : 76 }
{ "_id" : ObjectId("5e9c0ead6c954c74be91e6ca"), "Name" : "Bob", "Marks" : 67 }
{ "_id" : ObjectId("5e9c0eb76c954c74be91e6cb"), "Name" : "David", "Marks" : 98 }
Alternative: Direct Update Method
You can also update directly without forEach() for better performance ?
db.demo634.updateOne({Name: "David"}, {$set: {Marks: 98}});
Conclusion
The forEach() method allows you to traverse and update documents by finding specific criteria. However, for simple updates, using updateOne() directly is more efficient and recommended.
Advertisements
