replaceOne() (Replace a Document)
Last updated: 2026-10-09
replaceOne() (Replace a Document)
replaceOne() swaps the first document matching a filter for an entirely new document. Unlike updateOne(), whose second argument uses update operators, here the second argument is the replacement document itself — every field except _id is overwritten. The result includes matchedCount and modifiedCount. It is the right tool when a document's structure must be rewritten wholesale.
| Category | Write |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.replaceOne(<filter>, <replacement>, { upsert: <bool> })
⚙️ Parameters
| filter | Predicate matching the document to replace. |
|---|---|
| new document | The full replacement document; overwrites all fields except _id. |
| upsert | Optional. Insert when nothing matches; default false. |
Returns:UpdateResult: { acknowledged, matchedCount, modifiedCount, upsertedId }.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// replaceOne: replace Bob's document wholesale
db.users.replaceOne(
{ name: 'Bob' },
{ name: 'Bob', age: 26, city: 'Shanghai', vip: true }
)
Output:
{ acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedId: null }
📌 Notes
- The replacement must keep the _id (or omit it so the original survives) or an error is thrown
- Update operators like {$set: ...} are not interpreted here — they would be stored as literal fields
- Only the first match is replaced; loop or use updateMany() for batch work
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between replaceOne and updateOne?
AupdateOne() changes fields incrementally with operators; replaceOne() swaps in a whole new document, overwriting every field except _id.
QCan replaceOne change the _id?
ANo. _id is immutable; the replacement must keep the original _id or an error is thrown.
QCan update operators go in replaceOne's second argument?
ANo. The second argument is the replacement document; {$set: ...} would be stored literally as a field.