The updateOne()
and updateMany()
methods are used to modify existing documents in a MongoDB collection.
Updates the first document that matches the filter.
db.students.updateOne( { name: "Amit" }, { $set: { age: 25 } } );
This updates the age
field to 25 for the first student named "Amit".
Updates all documents that match the filter.
db.students.updateMany( { age: { $lt: 18 } }, { $set: { status: "minor" } } );
This sets the status
field to "minor" for all students younger than 18.
Increment the age
by 1 for a student named "Riya":
db.students.updateOne( { name: "Riya" }, { $inc: { age: 1 } } );
Replace the whole document of the student named "Raj" (be careful with this):
db.students.replaceOne( { name: "Raj" }, { name: "Raj", age: 23, status: "active" } );
updateOne(filter, update)
updates the first matching document.updateMany(filter, update)
updates all matching documents.$set
sets new values to fields.$inc
increments numeric fields.replaceOne()
replaces the entire document (careful with this!).Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!