← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 5 of 7

replaceOne()

replaceOne swaps a whole document for a new one, keeping only the _id.

In this page:

  1. replaceOne()
Syntax
javascript
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()

bash
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
  1. Using replaceOne for a small change
  2. Including operators in the replacement
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.