0
0
MongoDBquery~5 mins

updateMany method in MongoDB

Choose your learning style9 modes available
Introduction
The updateMany method changes multiple documents in a collection at once. It helps you fix or add data quickly without changing one by one.
You want to mark all orders as shipped for a specific customer.
You need to increase the price of all products in a category.
You want to add a new field to many user profiles at the same time.
You need to fix a typo in many documents' fields.
You want to reset a status for all tasks that are overdue.
Syntax
MongoDB
db.collection.updateMany(filter, update, options)
filter: Selects which documents to update.
update: Describes the changes to apply, usually with $set or other operators.
Examples
Sets the status to 'minor' for all users younger than 18.
MongoDB
db.users.updateMany({ age: { $lt: 18 } }, { $set: { status: "minor" } })
Adds 10 to the stock of all products in the 'books' category.
MongoDB
db.products.updateMany({ category: "books" }, { $inc: { stock: 10 } })
Marks all orders as not shipped.
MongoDB
db.orders.updateMany({}, { $set: { shipped: false } })
Sample Program
This example adds 500 to the salary of all employees in the sales department. It first inserts three employees, then updates the sales team salaries.
MongoDB
db.employees.insertMany([
  { name: "Alice", department: "sales", salary: 5000 },
  { name: "Bob", department: "sales", salary: 4500 },
  { name: "Charlie", department: "hr", salary: 4000 }
])

const result = db.employees.updateMany(
  { department: "sales" },
  { $inc: { salary: 500 } }
)

result.modifiedCount
OutputSuccess
Important Notes
updateMany changes all documents matching the filter, unlike updateOne which changes only one.
If no documents match the filter, updateMany does nothing but still returns a result.
Use update operators like $set, $inc, $unset inside the update argument to specify changes.
Summary
updateMany updates multiple documents at once based on a filter.
You must use update operators like $set or $inc to change fields.
It returns how many documents were changed.