MongoDB – db.collection.findOneAndReplace() Method
The findOneAndReplace()
method in MongoDB is a powerful tool for finding and replacing a single document within a collection. This method replaces the first document that matches the specified criteria with a new one. By default, it returns the original document but this can be configured to return the new document.
MongoDB findOneAndReplace() Method
The findOneAndReplace() method replaces the first matched document based on the selection criteria. By default, this method returns the original document. To return the replacement document, set the value of the returnNewDocument option to true.
It takes eight parameters, the first parameter is the selection criteria and the second parameter is the replacement document. And the others are optional. Using this method we can also replace embedded documents. We can also use this method in multi-document transactions.
Syntax:
db.Collection_name.findOneAndReplace(
selection_criteria: <document>, // The filter criteria to find the document
replacement: <document>, // The new document to replace the found document
{
projection: <document>, // Optional: Fields to include or exclude in the returned document
sort: <document>, // Optional: Sort the documents before applying the replacement
maxTimeMS: <number>, // Optional: Maximum time in milliseconds to allow the operation to run
upsert: <boolean>, // Optional: If true, insert a new document if no document matches the filter
returnNewDocument: <boolean>, // Optional: If true, return the updated document instead of the original
collation: <document> // Optional: Collation settings to specify language-specific rules
}
)
Parameters:
- The first parameter is the selection criteria for replacing the document with the new document.
- The second parameter is the replacement document.
- The third parameter is optional.
Optional Parameters:
- projection: The type of this parameter is document. It determines which fields are returned to the matching documents. This document takes:
{ field1: <value1>, field2: <value2> ... }
Here if the value of the field is 1/true then it specifies the inclusion of the field, or if the value of the field is 0/false then it specifies the exclusion of the field.
- sort: It determines which document the operation will modify if the query selects multiple documents. findOneAndReplace() will replace the first document in the sort order specified by this argument. The type of this parameter is document.
- maxTimeMS: The type of this parameter is number. It specifies the time limit in milliseconds within which the operation must complete. It throws an error if the time limit is exceeded.
- upsert: The default value of this parameter is false. If the value of this option is set to true and no document matches the given filter query, then this method creates a new document from the replacement parameter and returns null(after inserting a new document) unless the value of returnNewDocument option is set to true. Or if the value of this upsert option is set to true, then this method replaces the document that matches the given filter query with the replacement document.
- returnNewDocument: The type of this parameter is boolean. By default, this method returns the original document. To return the replacement document, use the returnNewDocument option and set its value to true.
- Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
Return Value
By default, this method returns the original document before replacement. To return the new document use the returnNewDocument option and set its value to true.
Examples of MongoDB findOneAndReplace() Method
In the following examples, we are working with:
- Database: gfg
- Collections: student
- Document: Four documents contains name and the age of the students
Example 1: Replace the first matched document whose age is 17 and returns replaced document
This example finds the first document where age
is 17 and replaces it with a new document { name: "Mihir", age: 17 }
. It returns the original document before replacement.
Query:
db.student.findOneAndReplace({age:17},{name:"Mihir", age:17})
Before replacement:
After replacement:
Explanation: we find a document that matches the given filter query(i.e., age:17) from the student collection and then replace the matched document with a new document(i.e., {name:”Mihir”, age:17}) using the findOneAndReplace() method. Here, this method returns the original document.
Example 2: Replace the first matched document whose age is 17 and returns a new document
This example replaces a document where age
is 17 and ensures that the updated document is returned instead of the original.
Query:
db.student.findOneAndReplace({age:17},{name:"Sagar", age:17},
{returnNewDocument:true})
Output

Explanation:
Here, we find a document that matches the given filter query(i.e., age:17) from the student collection and then replace the matched document with a new document(i.e., {name:”Sagar”, age:17}) using the findOneAndReplace() method. Here, this method returns the new document because the value of the returnNewDocument option is set to true.
Important Points
- The
findOneAndReplace()
method finds and replaces the first document that matches the selection criteria. - By default, it returns the original document, but you can configure it to return the new document.
- The method provides optional parameters like
projection
,sort
,maxTimeMS
,upsert
,returnNewDocument
, andcollation
to customize its behavior. - It can be used for atomic updates and multi-document transactions.
- Using
upsert: true
, the method can insert a new document if no match is found.
Conclusion
The db.collection.findOneAndReplace()
method is a powerful tool for replacing documents in MongoDB. Its ability to return either the original or the new document makes it flexible for various applications. Understanding its syntax, parameters, and use cases will help us make the most out of this method for efficient document management in MongoDB. By mastering this method, developers can ensure atomicity in updates and simplify document replacement operations in MongoDB databases
FAQs
What does findOneAndReplace
do?
The
findOneAndReplace
method finds a single document in a MongoDB collection that matches the specified filter criteria and replaces it with a new document. By default, it returns the original document before the replacement. However, you can modify this behavior to return the newly replaced document by setting the `returnNewDocument` option to true.
What is the difference between findOneAndReplace
and replaceOne
?
The primary difference between
findOneAndReplace
andreplaceOne
is thatfindOneAndReplace
returns the document before or after the replacement operation, depending on thereturnNewDocument
option. In contrast,replaceOne
only returns information about the operation’s success and does not return the replaced document. Additionally,findOneAndReplace
is useful when you need to return the replaced document or the original document as part of the operation.
Can the findOneAndReplace
method be used in multi-document transactions?
Yes, the
findOneAndReplace
method can be used in multi-document transactions. This allows you to perform the find-and-replace operation within a broader transaction that includes multiple operations, ensuring atomicity and consistency across all affected documents.