Open In App

MongoDB – db.collection.findOneAndReplace() Method

The findOneAndReplace() method replaces the first matched document based on the given 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 selection criteria and the second parameter is the replacement document. And the others are optional. Using this method you can also replace embedded documents. You can also use this method in multi-document transactions.

Syntax:



db.Collection_name.findOneAndReplace(

selection_criteria:<document>,



replacement: <document>,

{

    projection: <document>,

    sort: <document>,

    maxTimeMS: <number>,

    upsert: <boolean>,

    returnNewDocument: <boolean>,

    collation: <document>

  }) 

Parameters:

Optional Parameters:

{ 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:

By default, this method returns the original document. To return the replacement document, use the returnNewDocument option and set its value to true.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Four documents contains name and the age of the students

db.student.findOneAndReplace({age:17},{name:"Mihir", age:17})

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:”Mihir”, age:17}) using the findOneAndReplace() method. Here, this method returns the original document.

After replacement:

db.student.findOneAndReplace({age:17},{name:"Sagar", age:17},
                             {returnNewDocument:true})

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.

After replacement:

Article Tags :