Open In App

MongoDB – FindAndModify() Method

The findAndModify() method in MongoDB modifies and returns a single document that matches the given criteria. By default, db.collection.findAndModify(document) method returns a pre-modification document.

To return the document with the modifications made on the update, use the new option and set its value to true. It takes a document as a parameter.



Important Points:

“field.nestedfieldname”: <value>

or



{field: {nestedfieldname: <value>}}

MongoDB FindAndModify() Method Sntax

db.Collection_name.findAndModify(
{
    selection_criteria:<document>,
    sort: <document>,
    remove: <boolean>,
    update: <document>,
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>,
    bypassDocumentValidation: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [ <filterdocument1>, ... ]
})

Parameters:

Optional Parameters:

Return:

MongoDB FindAndModify Method Examples

Let’s look at some MongoDB FindandModify examples. In the following examples, we are working with:

Database: gfg

Collections: student

Document: Three documents contains name, language they use in coding and the score they got by solve problem on gfg.

Update Value using FindandModify Method Example

We are increasing marks by 4 whose name is vishal.

Query:

db.student.findAndModify({query:{name:"vishal"},update:{$inc:{score:4}}})

Output:

After update:

Get the Modified Document after the FindandModify Method Example

 db.student.findAndModify({query:{name:"vishal"},
                          update:{$inc:{score:4}},new:true})

Here, we are again increasing the value of the score field by 4 of the document whose name is “vishal” but this time we set the value of new to true, and the findAndModify() method returns the modified document.

After update:

Article Tags :