How to Use the findOneAndUpdate() Method in MongoDB
-
Use the
findOneAndUpdate()
Method in MongoDB -
Use the
findOneAndUpdate()
Method to Update the First Matched Document -
Use the
findOneAndUpdate()
Method to Update the Value of the Embedded Document -
Use the
findOneAndUpdate()
Method to Update the First Matched Document and Return the Updated Document - Conclusion
This article will introduce the the findOneAndUpdate()
method in MongoDB. We will use this method to update the first matched and embedded documents.
Use the findOneAndUpdate()
Method in MongoDB
The method db.collection.findOneAndUpdate()
updates the collection’s matching document according to a selection criteria. This method will only update the first document that matches the selection criteria if there are more than one document matches.
The value of the _id
field does not change when you update the document.
This method will return the original document; however, you must specify the value of the returnNewDocument
parameter to true
if you want the updated document to be returned.
You can use this method to replace embedded documents. This approach can also be used in multi-document transactions.
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,
selection_criteria
, is the selection criteria for the update. The type for this parameter is a document. - The second parameter,
update_data
, is a document to be updated. The type for this parameter is a document. - The third parameter is optional.
Optional Parameters:
-
projection
: The type for this parameter is a document. The projection parameter will determine which fields are returned to the matching documents.This document takes the following values:
{ field1: <boolean>, field2: <boolean> ... }
If the field’s value is
1
ortrue
, it indicates that the field is included, and if the field’s value is0
orfalse
, the field is excluded.
-
sort
: This will determine which document the operation will modify if the query selects multiple documents. Thedb.collection.findOneAndUpdate()
method will update the first document in the sort order specified by this argument.The type for this parameter is a document.
-
maxTimeMS
: The type for this parameter is number. It will specify the time limit in milliseconds within which the operation must be complete.It will return an error if the time limit is exceeded.
-
upsert
: The default value of this parameter isfalse
.Suppose the value of this option is set to
true
and no document matches the given filter query. In that case, this method creates a new document.It returns a
null
value (after inserting a new document) unless the value of thereturnNewDocument
option is set to betrue.
Or if the value for thisupsert
option is set to betrue,
then this method will update the document that matches the given filter query. -
returnNewDocument
: This parameter type is a boolean. By default, this method will return the original document.Use the
returnNewDocument
parameter and set its value totrue
to return the updated document. -
Collation
: It specifies the use of the collation for operations. It allows users to determine the language-specific rules for string comparison, like rules for letter cases and accent marks.The type for this parameter is a document.
-
arrayFilters
: An array of filter documents indicates which array elements are to be modified for an update operation on an array field. The type for this parameter is an array.
It will return the original document, but if you want to return the updated document, you will have to set the value of the returnNewDocument
parameter to true
.
In the following examples, you will work with the following database. You will create a collection called students
with documents containing the students’ details.
The database is given below:
db={
"students": [
{
id: 1,
name: "Ali",
language: "JavaScript",
score: 82
},
{
id: 2,
name: "Haris",
language: "Python",
score: 91
},
{
id: 3,
name: "Hamza",
language: "Python",
score: {
"Physics": 84,
"Math": 85
}
}
]
}
Use the findOneAndUpdate()
Method to Update the First Matched Document
For this example, you will use the query given below:
db.students.findOneAndUpdate({name:"Ali"},{$inc:{score:4}})
Here, you will update the first matched document according to the selection criteria (i.e., name: "Ali"
) by a new document (i.e., {$inc:{score:4}
}. The value of the score
field is increased by four, and it returns the original document.
Output:
After updating the document, it will return this output.
Use the findOneAndUpdate()
Method to Update the Value of the Embedded Document
For this example, you will use the query given below:
db.student.findOneAndUpdate({name:"Hamza"},{$inc:{"score.Math":5}})
Here, you will update the value of the Math
field in the embedded document. The value of the Math
field is increased by five.
Output:
Use the findOneAndUpdate()
Method to Update the First Matched Document and Return the Updated Document
For this example, you will use the query given below:
db.student.findOneAndUpdate({name:"Ali"},{$inc:{score:5}},{returnNewDocument:true})
Here, you will update the first matched document according to the selection criteria (i.e., name: "Ali"
) by a new document (i.e., {$inc:{score:5}
}. The value of the score
field is increased by five.
It returns the newly updated document because we set the value of the returnNewDocument
to true
.
Output:
Conclusion
Through the help of this MongoDB tutorial article, you have learned how to use the db.collection.findOneAndUpdate()
method, which is used to update the first matched document in the collection that matches the selection criteria. You can also use this method to replace embedded documents and also use it in multi-document transactions.