updateMany()
updateMany changes every document that matches the filter.
In this page:
Syntax
db.collection_name.updateMany(
filter,
{ $set: { field: new_value } }
)
updateMany()
Use updateMany for bulk changes such as marking old records or applying a price increase. An empty filter {} matches all documents, so double check filters before running. The result gives how many documents matched and changed.
Note:
Run the filter with find first to preview which documents will change.
Example: updateMany()
test> db.products.insertMany([
... { _id: 1, name: "Pen", price: 3, category: "office" }, { _id: 2, name: "Desk", price: 150, category: "furniture" },
... { _id: 3, name: "Notebook", price: 8, category: "office" }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.products.updateMany({ category: "office" }, { $set: { onSale: true } })
{ acknowledged: true, matchedCount: 2, modifiedCount: 2 }
test> db.products.find({ onSale: true }, { name: 1, _id: 0 })
[ { name: 'Pen' }, { name: 'Notebook' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using an empty filter by accident
- Forgetting operators
- Not previewing the affected documents
Chapter Summary
- updateMany affects all matches
- {} matches everything
- Preview with find first
- Result reports matched and modified counts
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: