Update documents into MongoDB collection you can use two methods in the MongoDB shell or in your application.
- updateOne()
- updateMany()
1. updateOne()-
You used updateOne() to update a single document into a collection.
db.collection.updateOne(
{ <filter> },
{ $set: { <update> } }
)
filter - Filter criteria to match documents
update - Update operation
Example:
db.users.updateOne(
{ name: "Mahendra Pratap Singh" },
{ $set: { age: 31 } }
)
Update the age of a user named "Mahendra Pratap Singh
" to 31:
2. updateMany()-
db.users.updateMany(
{ age: { $gt: 25 } },
{ $set: { status: "active" } }
)
MongoDB provides various update operators like $set, $unset, $inc, $push, etc., to perform specific update operations.