LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1515 min read

Updating Documents

Modify existing documents using updateOne, updateMany, and replaceOne.

updateOne

updateOne() modifies the first document matching a filter, using update operators (covered in depth next) to describe exactly what changes.

db.users.updateOne(
{ email: "ada@example.com" },
{ $set: { age: 29 } },
);

updateMany

updateMany() applies the same update to every document matching a filter.

db.products.updateMany(
{ category: "electronics" },
{ $set: { onSale: true } },
);

replaceOne

replaceOne() replaces an entire matching document with a new one — unlike updateOne, it doesn't merge changes into the existing document; it wholesale substitutes it (keeping the same _id).

db.users.replaceOne(
{ email: "ada@example.com" },
{ name: "Ada Lovelace", email: "ada@example.com", age: 29 }, // completely replaces the document
);
replaceOne Drops Unlisted Fields

Any field on the original document not included in the replacement document is simply gone afterward — this is the key difference from updateOne with $set, which only touches the fields you specify.

Understanding the Update Result

db.users.updateOne({ email: "ada@example.com" }, { $set: { age: 29 } });
Shell Result

Click Run to see what this code prints.

matchedCount tells you how many documents matched the filter; modifiedCount tells you how many were actually changed — these can differ if the update would have set a field to the value it already had.

Common Beginner Mistakes

Passing a plain document as the update, expecting a merge

db.users.updateOne({ ... }, { age: 29 }) throws an error — a bare document without an operator like $set is treated as an attempted full replacement, and MongoDB rejects it in updateOne/updateMany for safety.

Using updateOne when you meant updateMany

updateOne only touches the first matching document — double-check which one you intend when a filter could match several.

FAQs

Whichever one the query naturally returns first, based on its internal storage/index order — if you need a specific one, filter precisely enough (often by _id) to match exactly one.

Yes — the filter argument for update operations uses exactly the same query operators covered in the query operators lesson.

Summary

updateOne/updateMany modify fields on existing documents, while replaceOne substitutes an entire document. Next, you'll go deep on the update operators — like $set and $inc — that describe exactly what changes.

Next Lesson →

Update Operators