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:
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:
- If you want to find fields of the embedded document, then use the following syntax:
“field.nestedfieldname”: <value>
or
{field: {nestedfieldname: <value>}}
- The document returned by this method always contains the _id field. If you don’t want the _id field, then set _id:0 in the projection.
- You can use this method in multi-document transactions.
- If you are using this method, in shared collection, then the query expression must contain an equality condition on the shared key.
Contact Us