0
0
MongodbHow-ToBeginner · 4 min read

How to Use replaceOne in MongoDB: Syntax and Examples

Use replaceOne(filter, replacement, options) in MongoDB to replace a single document matching the filter with a new replacement document. This method updates the entire document except for the _id field unless changed explicitly.
📐

Syntax

The replaceOne method requires three main parts:

  • filter: A query object to find the document to replace.
  • replacement: The new document that will replace the matched document.
  • options (optional): Additional settings like upsert to insert if no match is found.
javascript
db.collection.replaceOne(
  { filter },
  replacement,
  { upsert: false }
)
💻

Example

This example replaces a user document with a new one based on the user's name.

javascript
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  try {
    await client.connect();
    const db = client.db('testdb');
    const users = db.collection('users');

    // Replace the document where name is 'Alice'
    const result = await users.replaceOne(
      { name: 'Alice' },
      { name: 'Alice', age: 30, city: 'New York' },
      { upsert: false }
    );

    console.log('Matched count:', result.matchedCount);
    console.log('Modified count:', result.modifiedCount);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
Matched count: 1 Modified count: 1
⚠️

Common Pitfalls

Common mistakes when using replaceOne include:

  • Trying to update only some fields instead of replacing the whole document. Use updateOne for partial updates.
  • Not including the _id field in the replacement document, which MongoDB keeps unchanged automatically.
  • Forgetting to set upsert: true if you want to insert a new document when no match is found.
javascript
/* Wrong: Partial update with replaceOne (will remove other fields) */
db.collection.replaceOne(
  { name: 'Alice' },
  { age: 30 } // This removes all other fields except _id
);

/* Right: Use updateOne for partial updates */
db.collection.updateOne(
  { name: 'Alice' },
  { $set: { age: 30 } }
);
📊

Quick Reference

ParameterDescriptionExample
filterQuery to find the document to replace{ name: 'Alice' }
replacementNew document to replace the old one{ name: 'Alice', age: 30, city: 'NY' }
optionsOptional settings like upsert{ upsert: true }

Key Takeaways

Use replaceOne to fully replace a single document matching a filter.
The replacement document must include all fields you want to keep except _id.
Set upsert: true to insert if no matching document is found.
For partial updates, use updateOne with $set instead of replaceOne.
replaceOne returns matchedCount and modifiedCount to check operation success.