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" } }
)Operation
| Operator | Purpose |
|---|---|
$set | Set or update a field |
$unset | Remove a field |
$inc | Increase/decrease a numeric value |
$rename | Rename a field |
$push | Add an element to an array |
$pull | Remove an element from an array |