← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 2 of 7

updateMany()

updateMany changes every document that matches the filter.

In this page:

  1. updateMany()
Syntax
javascript
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()

bash
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
  1. Using an empty filter by accident
  2. Forgetting operators
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.