mongodb update many
- Published
- Reading time
- 1 min read
- Length
- 225 words
On this page
MongoDB Update Many#
If you want to update multiple documents in MongoDB, you can use the updateMany() method. This method will update all documents matching the specified filter.
Syntax#
db.collection.updateMany(filter, update, options)filter: Specifies the selection criteria for the update. This parameter uses the same syntax as thefind()method.update: Specifies the modifications to apply.options: Optional. Specifies additional options, such as sort order and limit.
Example#
Suppose you have a collection called "users" with the following documents:
{
"_id": ObjectId("5f63a8c1d28f1e3e3c3e8ea8"),
"name": "John",
"age": 30
}
{
"_id": ObjectId("5f63a8c1d28f1e3e3c3e8ea9"),
"name": "Jane",
"age": 25
}
{
"_id": ObjectId("5f63a8c1d28f1e3e3c3e8eaa"),
"name": "Bob",
"age": 40
}If you want to update the age of all users with the name "John", you can use the following command:
db.users.updateMany(
{ name: "John" },
{ $set: { age: 35 } }
)This will update all documents with the name "John" and set their age to 35.
You can also use the $inc operator to increment a field by a certain value. For example, if you want to add 5 to the age of all users with the name "Jane", you can use the following command:
db.users.updateMany(
{ name: "Jane" },
{ $inc: { age: 5 } }
)This will update all documents with the name "Jane" and add 5 to their age.
Remember to always use caution when updating multiple documents at once, as it can have unintended consequences.