MongoDB findAndModify() Method (original) (raw)

Last Updated : 5 May, 2026

findAndModify() is an atomic MongoDB operation that updates, removes, or upserts a single matching document and returns it, ensuring safe read-modify-write behavior in concurrent environments.

Syntax

db.Collection_name.findAndModify(
{
query:,
sort: ,
remove: ,
update: ,
new: ,
projection: ,
upsert: ,
bypassDocumentValidation: ,
writeConcern: ,
collation: ,
arrayFilters: [ , ... ]
})

Return Value of findAndModify()

Examples of MongoDB findAndModify Method

In the following examples, we are working with:

Screenshot-2026-02-06-154736

Example 1: Update a Document

To increase the score of a student named Maria by 4.

**Query:

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

**Output:

Screenshot-2026-02-06-155956

Example 2: Return the Modified Document

Find and modify the document for the student with the name Maria in the student collection by incrementing the score field by 4. Return the modified document.

**Query:

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

**Output:

Screenshot-2026-02-06-160313

Example 3: Update and Return the Updated Document (Using findOneAndUpdate())

Update Maria’s score to 220 and return the modified document.

**Query:

db.student.findOneAndUpdate(
{ name: "Maria" },
{ $set: { score: 220 } },
{ returnDocument: "after" }
)

**Output:

Screenshot-2026-02-06-161452

Note: findOneAndUpdate() is the modern, recommended alternative to findAndModify() for update operations and provides a cleaner API to return the updated document.

Example 4: Upsert Operation (Using updateOne())

Updates the document for the student with the name "Jenny" in the students collection. If no document matches the query, insert a new document with the name "Jenny", setting the language to "C#" and the score to 195.

**Query:

db.student.updateOne(
{ name: "Jenny" },
{ $set: { lang: "C#", score: 195 } },
{ upsert: true }
)

**Output:

Screenshot-2026-02-06-162534

**Note: updateOne() with upsert: true is the recommended way to insert a document when no match is found, instead of using findAndModify() for upserts.

Best Practices for Using findAndModify()

To get the most out of MongoDB's findAndModify() method, consider the following best practices: