MongoDB – db.collection.findOneAndUpdate() Method
Last Updated :
10 Oct, 2024
The MongoDB findOneAndUpdate()
method is used to update the first matched document in a collection based on the selection criteria. It offers various options such as sorting, upserting and returning the updated document.
In this article, We will learn about MongoDB findOneAndUpdate() in detail by understanding various examples and so on.
MongoDB findOneAndUpdate()
- The MongoDB findOneAndUpdate() method updates the first matched document in the collection that matches the selection criteria.
- If more than one document matches the selection criteria then it updates only the first matched document. When we update the document, the value of the _id field remains unchanged.
- This method will return the original document but if we want to return the updated document then we have to set the value of the returnNewDocument parameter to true.
- It takes three parameters, the first one is the selection criteria, the second one is the new data to be updated and the remaining are optional.
- Using this method we can also replace embedded documents. We can also use this method in multi-document transactions.
To learn more about updating data in full-stack applications, the Full Stack Development with Node JS course covers practical examples of handling updates in MongoDB with Node.js.
Syntax:
db.collection.findOneAndUpdate(
selection_criteria: <document>,
update_data: <document>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>,
arrayFilters: [ <filterdocument1>, … ]
})
Parameters:
- The first parameter is the selection criteria for the update. The type of this parameter is document.
- The second parameter is a document that to be updated. The type of this parameter is document.
- The third parameter is optional.
Optional Parameters:
- projection: The type of this parameter is document. The projection parameter 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. findOneAndupdate() will update 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 will give an error if the 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 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 updates the document that matches the given filter query.
- returnNewDocument: The type of this parameter is boolean. By default, this method returns the original document. To return the updated document, use the returnNewDocument 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.
- arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
Return:
It returns the original document but if we want to return the updated document then we have to set the value of the returnNewDocument parameter to true.
Examples of MongoDB findOneAndUpdate()
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Three documents contains the details of the students
Output:
Example 1: Update A Document
db.student.findOneAndUpdate({name:"Nikhil"},{$inc:{score:4}})
Here, we update the first matched document according to the selection criteria(i.e., name:”Nikhil”) by a new document(i.e., {$inc:{score:4}} – the value of the score field is increase by 4) and return the original document:
After update:
Example 2: Update Embedded Document
db.student.findOneAndUpdate({name:"Ashok"},{$inc:{"score.math":50}})
Here, we update the value of the math field in the embedded document.
After update:
Example 3: Update Document and return the Updated Document
db.student.findOneAndUpdate({name:"Vishal"},{$inc:{score:4}},{returnNewDocument:true})
Here, we update the first matched document according to the selection criteria(i.e., name:”Vishal”) by a new document(i.e., {$inc:{score:4}} – the value of the score field is increase by 4) and return the new updated document because we set the value of the returnNewDocument to true.
Output:
Example 4: Update Document with Upsert
Let’s Update the document for “John” to set the language to “Java” and score to 300, or insert a new document if “John” does not exist.
db.student.updateOne(
{ name: "John" },
{ $set: { language: "Java", score: 300 } },
{ upsert: true }
);
Output:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1, "upsertedId" : { "_id" : ObjectId("60226a70f19652db63812e8a") } }
Explanation: This query updates the document where the name
is “John” to set the language
to “Java” and score
to 300. If no document matches, it inserts a new document with these values (upsert
).
Example 5: Sort And Update A Document
Let’s Find the student with the highest score and update their language to “JavaScript”
db.student.find().sort({ "score": -1 }).limit(1).forEach(function(doc) {
db.student.updateOne({ "_id": doc._id }, { $set: { language: "JavaScript" } });
});
Output:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Explanation: This query sorts the documents by score
in descending order and updates the first document found by setting the language
to “JavaScript“.
Conclusion
findOneAndUpdate()
is a powerful method in MongoDB for updating documents, especially when you need to update a single document based on specific criteria. Understanding its various options and parameters can help in efficiently managing your MongoDB collections.
FAQs on MongoDB findOneAndUpdate()
Can findOneAndUpdate()
update multiple documents?
findOneAndUpdate()
updates only the first document that matches the selection criteria.
How can I update a document and retrieve the updated version in MongoDB?
Set the returnNewDocument
option to true
in the method call.
What is the purpose of the upsert
option in findOneAndUpdate()
?
The upsert
option allows you to insert a new document if no document matches the selection criteria.
Can findOneAndUpdate()
update embedded documents?
Yes, findOneAndUpdate()
can update embedded documents within a document