Open In App

MongoDB – db.collection.findOneAndUpdate() Method

The findOneAndUpdate() method updates the first matched document in the collection that matches the selection criteria. If more than one document matched 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 you can also replace embedded documents. You can also use this method 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:

Optional Parameters:

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.

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:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Three documents contains the details of the students

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:

db.student.findOneAndUpdate({name:"Ashok"},{$inc:{"score.math":50}})

Here, we update the value of the math field in the embedded document.

After update:

 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. 

Article Tags :