top of page
  • Writer's pictureBalaaji Dhananjayan

Difference between update(), updateOne() and updateMany() in MongoDB

As I read through some of the blog posts, there are many people out there, who ask for what is the difference between what is update(), updateOne() & updateMany() in MongoDB. Lets discuss what they actually mean and where can you refer more info on the same.


db.collections.update():

This basically modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter and filters set to it. By default, the db.collection.update() method updates a single document. Include the option multi: true (this is equivalent to updateMany() which we will discuss below) to update all documents that match the query criteria.

Eg:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>, // Added in MongoDB 4.2
     let: <document> // Added in MongoDB 5.0
   }
)

For more info: Click here


db.collections.updateOne()


In this case, it updates a single document within the collection based on the filter. Well, it's one document that meets the criteria first if you have more than 1 document meeting the search criteria. Consider what happens if you give findOne(). Typically, in a clean env, it should be only 1 document for the purpose of the operator and can be easily met if the "_id" is mentioned. This method is a new feature from 3.2 and this effectively replaces the use of update().

Eg:

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

For more info: Click here


db.collections.updateMany():


This one updates all documents that match the specified filter for a collection. Again, this method is a new feature from 3.2 and this effectively replaces the use of update() along with option multi: true.


Eg:

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

More info: Click here


Hope this info helps to understand more on update collections methods.


Have a good day!!


Regards,

Balaaji Dhananjayan

1,577 views0 comments
bottom of page