How to Use findOneAndReplace in MongoDB: Syntax and Example
Use
findOneAndReplace(filter, replacement, options) in MongoDB to find a single document matching filter and replace it entirely with replacement. You can specify options like returnDocument to get the document before or after replacement.Syntax
The findOneAndReplace method takes three main parts:
- filter: A query to find the document to replace.
- replacement: The new document that will replace the found one.
- options: Optional settings like
returnDocumentto control the returned document.
This method replaces the entire document, not just some fields.
javascript
db.collection.findOneAndReplace(filter, replacement, options)
Example
This example finds a user with { name: 'Alice' } and replaces her document with a new one containing updated fields. It returns the new document after replacement.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); // Insert a sample document await users.insertOne({ name: 'Alice', age: 25, city: 'New York' }); // Replace the document where name is 'Alice' const result = await users.findOneAndReplace( { name: 'Alice' }, { name: 'Alice', age: 26, city: 'Boston' }, { returnDocument: 'after' } ); console.log(result.value); await client.close(); } run();
Output
{"name":"Alice","age":26,"city":"Boston","_id":"<ObjectId>"}
Common Pitfalls
Common mistakes when using findOneAndReplace include:
- Not including the
_idfield in the replacement document, which MongoDB adds automatically. - Expecting partial updates;
findOneAndReplacereplaces the whole document, so missing fields are removed. - Forgetting to set
returnDocument: 'after'if you want the updated document returned instead of the original.
javascript
/* Wrong: partial update - this removes other fields */ db.collection.findOneAndReplace( { name: 'Alice' }, { age: 30 }, // This replaces entire document, removing 'name' and '_id' { returnDocument: 'after' } ); /* Right: include all fields you want to keep */ db.collection.findOneAndReplace( { name: 'Alice' }, { name: 'Alice', age: 30 }, { returnDocument: 'after' } );
Quick Reference
- filter: Query to find the document.
- replacement: New document to replace the old one.
- options.returnDocument: 'before' (default) or 'after' to return the document before or after replacement.
- options.upsert: true to insert if no document matches.
Key Takeaways
Use findOneAndReplace to replace an entire document matching a filter in MongoDB.
Always provide the full replacement document; partial updates are not supported by this method.
Set returnDocument: 'after' option to get the updated document returned.
Remember that _id is preserved automatically; do not remove it in the replacement.
Use upsert option to insert a new document if no match is found.