replaceOne()
replaceOne swaps a whole document for a new one, keeping only the _id.
In this page:
Syntax
db.collection_name.replaceOne(filter, { field1: value1, field2: value2 })
replaceOne()
Unlike updateOne, replaceOne takes a full replacement document with no operators. Every field not in the new document disappears. It is useful when you want an exact new shape but dangerous if you meant a partial change.
Note:
Use replaceOne only when you intend to overwrite everything except _id.
Example: replaceOne()
test> db.users.insertOne({ _id: 1, name: "Ada", age: 36, city: "London" })
{ acknowledged: true, insertedId: 1 }
test> db.users.replaceOne({ _id: 1 }, { name: "Ada Lovelace", role: "mathematician" })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.users.findOne()
{ _id: 1, name: 'Ada Lovelace', role: 'mathematician' }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using replaceOne for a small change
- Including operators in the replacement
- Trying to change _id
Chapter Summary
- replaceOne overwrites the whole document
- _id is kept
- No update operators allowed
- Use updateOne for partial changes
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: