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.

CategoryWrite
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.replaceOne(<filter>, <replacement>, { upsert: <bool> })

⚙️ Parameters

filterPredicate matching the document to replace.
new documentThe full replacement document; overwrites all fields except _id.
upsertOptional. 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏