Open In App

Difference Between findAndModify and Update in MongoDB?

MongoDB, with its flexible documentbased data model, offers a range of methods for updating data within collections. Two of the most commonly used methods, findAndModify and update, each has its unique strengths and purposes. Understanding the differences between these methods can significantly impact the efficiency and effectiveness of our MongoDB operations. Let’s understand what is findAndModify and update along with their syntax, examples and so on.

What is the findAndModify() Method?

Syntax:



db.collection.findAndModify(
<query>,
<sort>,
<update>,
<options>
)

Explanation:

Example of findAndModify() Method

Suppose we have a gfg database in courses collection which stores information about various courses. Each document in the collection represents a course and contains details such as the course name, Instructore name, fees and duration.

After inserting record into the courses collection, Our courses looks like:



collection

Example 1: Let’s Find the Fees of Java Course to 25000 Otherwise Modified it

Here, we are modifying the value of field Fees of the Java course from 12000 to 25000 using the findAndModify method.

db.courses.findAndModify({
query: { Course: 'Java' },
update: { $set: { Fees: "25000" } }
});

Output:

Output

Note: findAndModify() method is deprecated in MongoDB starting from the 3.6 version.

Example 2: Let’s Find the Instructor of Python to Shree Otherwise Modified it

Here, we are modifying the value of field Instructor of the Python course from Shreya to Shree using the findAndModify method.

db.courses.findAndModify({
query: { Course: 'Python' },
update: { $set: { Instructor: 'Shree' } },
new: true
});

Output:

Output

What is the update() Method?

Syntax:

db.collection.update(
<filter>,
<update>,
<options>
)

Explanation:

Example of update() Method

Example 1: Update the Fees of Java Course to 25000

Here, we are modifying the value of field Fees of the Java course from 12000 to 25000 using the update method.

db.courses.update(
{ Course: 'Java' },
{ $set: { Fees: "25000" } }
);

Output:

Output

Example 2: Update the Instructor of Python to Shree

Here, we are modifying the value of field Instructor of the Python course from Shreya to Shree using the update method.

db.courses.update(
{ Course: 'Python' },
{ $set: { Instructor: 'Shree' } }
);

Output:

Output

Conclusion

Overall, MongoDB provides the findAndModify and update methods for updating data within collections, each with its own strengths and use cases. findAndModify is ideal for atomic operations where you need to read, update, and return a document in a single operation, while update is simpler and used for updating documents based on a query without returning the modified document.


Article Tags :