MongoDB – FindAndModify() Method
Last Updated :
17 Jun, 2024
The MongoDB findAndModify method is used to modify and return a single document that matches the given criteria. It can be used to update, remove or insert documents atomically. In this article, We will learn about the MongoDB findandmodify method in detail by understanding various examples and so on.
MongoDB findandmodify
- The MongoDB findandmodify method modifies and returns a single document that matches the given criteria.
- By default the 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 we 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.
- We can use this method in multi-document transactions.
- If we are using this method, in shared collection then the query expression must contain an equality condition on the shared key.
MongoDB findandmodify Syntax
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:
- remove: It is a must if the update field does not exist. If it is true, removes the selected document. The default value is false.
- update: It is a must if the remove field does not exist. Performs an update of the selected document. The update field employs the same update operators or field: value specifications to modify the selected document.
- Others are optional.
Optional Parameters:
- selection_criteria: It specifies the selection criteria for the modification. The query field employs the same query selectors as used in the db.collection.find() method. Although the query may match multiple documents, MongoDB findandmodify will only select one document to modify.
- sort: Determines which document the operation will modify if the query selects multiple documents. MongoDB findandmodify will modify the first document in the sort order specified by this argument.
- new: When true, returns the modified document rather than the original. The MongoDB findandmodify method ignores the new option for remove operations. The default is false.
- fields: A subset of fields to return. The fields document specifies an inclusion of a field with 1, as in the following:
- fields: { <field1>: 1, <field2>: 1, … }
- Upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method.
- writeConcern: It is only used when we do not want to use the default write concern. The type of this parameter is a document.
- Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
- arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
Return:
- Returns a single pre-modification document. To return the document with the modifications made on the update, use the new option and set it to true.
- If no document is found for an upsert, which means the command performs an insert, new is false, and the sort option is NOT specified, the method returns null.
- If no document is found for an upsert, which means the command performs an insert, and new is false, and a sort option is specified, the method returns an empty document {}.
Examples of MongoDB findandmodify Method
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.
Output:

Example 1: Update Value
We are increasing marks by 4 whose name is vishal.
Query:
db.student.findAndModify({query:{name:"vishal"},update:{$inc:{score:4}}})
Output:

Output:

Example 2: Get the Modified Document
Let’s Find and modify the document for the student with the name “vishal” in the student collection by incrementing the score field by 4. Return the modified document
db.student.findAndModify({query:{name:"vishal"},
update:{$inc:{score:4}},new:true})
Output:

Example 3: Update and Return
Let’s Find and update the document for the student with the name “vishal” in the students collection, setting the score to 220. Return the updated document.
db.students.findOneAndUpdate(
{ name: "vishal" },
{ $set: { score: 220 } },
{ returnDocument: "after" }
)
Output:
{
"_id" : ObjectId("60141912de51b19233bcb087"),
"name" : "vishal",
"lang" : "java",
"score" : 220
}
Example 4: Upsert: true
Let’s Update the document for the student with the name “john” in the students collection. If no document matches the query, insert a new document with the name “john”, setting the language to “Python” and the score to 195.
db.students.updateOne(
{ name: "john" },
{ $set: { lang: "Python", score: 195 } },
{ upsert: true }
)
Output:
{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : ObjectId("60c91514de51b19233bcb08a")
}
Conclusion
Overall, The findAndModify method in MongoDB is a powerful tool for making atomic changes to documents in a collection. It allows you to update, remove, or insert documents while ensuring that no other operations can modify the document in between.
MongoDB findandmodify – FAQs
How does the new option in findAndModify affect the returned document?
The new option, when set to true, returns the modified document after the update operation has been applied. If set to false, it returns the original document before the update.
What is the purpose of the upsert option in findAndModify?
The upsert option, when set to true, allows the findAndModify method to insert a new document if no document matches the query criteria. This is useful for ensuring that a document exists with certain values, even if it didn’t exist before.
Can findAndModify be used in transactions?
Yes, the findAndModify method can be used in multi-document transactions in MongoDB. This allows you to perform complex operations that involve multiple documents while ensuring that the changes are applied atomicall