CRUD
updateOne() and updateMany()
Updating documents by filter, matched versus modified counts, and when many is a mistake.
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" } }
){
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}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" } }
)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?
matchedCount is how many documents the filter hit. modifiedCount is how many actually changed. A match with no change is a no-op, not an error — the field was already that value.
Interview question
When is updateMany the wrong tool?
When you meant one user, one order, one product. A unique filter plus updateOne. updateMany is for a real set — every expired session, every SKU in a category — and the filter has to be reviewed like a DELETE.