![]() |
VOOZH | about |
MongoDB, with its flexible document-based 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.
Syntax:
db.collection.findAndModify(
<query>,
<sort>,
<update>,
<options>
)
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:
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:
Note: findAndModify() method is deprecated in MongoDB starting from the 3.6 version.
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:
Syntax:
db.collection.update(
<filter>,
<update>,
<options>
)
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:
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:
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.