All academies
Roadmap
LEVEL 3 · CRUD OPERATIONS

Updating & Deleting

12 min read

updateOne(filter, update) modifies the first match; updateMany modifies all matches. Updates use operators like $set, $inc, $push — without an operator you'd replace the whole document.

mongosh
db.products.updateOne(
  { name: "Wireless Mouse" },
  { $set: { price: 27.99 }, $inc: { stock: -1 } }
)

db.products.updateMany(
  { category: "office" },
  { $mul: { price: 0.9 } }   // 10% off everything
)

Upserts

Pass { upsert: true } to insert the document if nothing matches — perfect for counters and 'create or update' logic.

mongosh
db.pageviews.updateOne(
  { page: "/pricing" },
  { $inc: { views: 1 } },
  { upsert: true }
)

Deleting

deleteOne(filter) removes the first match, deleteMany(filter) removes all matches. deleteMany({}) empties the collection — the filter is required precisely so you must be explicit about that.

mongosh
db.products.deleteOne({ _id: 11 })
db.products.deleteMany({ stock: 0 })

Try it yourself

db.products.updateOne({ name: "Wireless Mouse" }, { $set: { price: 27.99 } })
Run in Shell

Check your understanding

Q1.

What does this do to the matched document { _id: 1, name: 'A', price: 10 }?

code
db.items.updateOne({ _id: 1 }, { price: 12 })
Q2.

Which option inserts a new document when the filter matches nothing?

Q3.

deleteMany({}) deletes every document in the collection.