ReplaceOne
ReplaceOne: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 16 of 100
ReplaceOne
Foundations & CRUD → Queries & Schema → Aggregation & Scale → Atlas & Projects
Foundations & CRUD · 1 — Documents · ~6 min · MongoDB — CRUD Operations
What is this?
replaceOne swaps the entire document (except _id) with a new one. Unlike updateOne with $set, fields you omit are removed.
Why should you care?
Form “Save profile” screens sometimes send the full object. Replace makes the stored document match that snapshot exactly.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.users.insertOne({ username: "kabir", city: "Delhi", bio: "old", score: 10 })
db.users.replaceOne(
{ username: "kabir" },
{ username: "kabir", city: "Mumbai", level: "pro" }
)
db.users.findOne({ username: "kabir" })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- After replaceOne, bio and score are gone because they were not in the replacement document.
- city is Mumbai and level is new.
- _id stays the same.
Practice next
- Insert kabir and replace as shown.
- Confirm bio is missing.
- Contrast with updateOne $set that keeps bio.
- Replace again adding bio back.
- Compare matchedCount when filter misses.
Remember
replaceOne overwrites the whole document. Omitted fields disappear. _id is preserved.
Admin edits full tenant config
A SaaS settings page posts the entire config object; the API replaceOne’s the tenants document.
Outcome: Removed toggles truly disappear instead of lingering as stale fields.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!