Skip to content

CRUD

updateOne() and updateMany()

Updating documents by filter, matched versus modified counts, and when many is a mistake.

BeginnerAbout 5 minutes

updateOne changes the first matching document. updateMany changes every match. The first argument is a filter, same as find. The second is an update document built from operators ($set, $inc, …) — the next lesson. You do not pass a full replacement here; that is replaceOne.

db.users.updateOne(
  { email: "rahul@example.com" },
  { $set: { city: "Pune" } }
)
Rahul moved. Only city changes; the rest of the document stays.
{
  acknowledged: true,
  matchedCount: 1,
  modifiedCount: 1
}
matchedCount is 'found it'. modifiedCount is 'the value actually changed'.

If city was already "Pune", you still get matchedCount: 1 and modifiedCount: 0. The write is a no-op, not a failure.

db.users.updateMany(
  { isActive: false },
  { $set: { role: "archived" } }
)
Every inactive user — think before you run this

update vs replace

replaceOne(filter, { name: "Rahul", city: "Pune" }) swaps the whole document (except _id). Fields you forgot are gone. updateOne with $set patches. In an API, patch with operators unless you truly mean replace.

Interview question

What is the difference between matchedCount and modifiedCount?

Think about it first.

Interview question

When is updateMany the wrong tool?

Think about it first.

Related lessons