mongodb bulk update

MongoDB Bulk Update

Bulk update is the process of updating multiple documents in a MongoDB collection at once. Updating each document one by one can be time-consuming and inefficient, especially when dealing with large datasets.

Using updateMany()

MongoDB provides the updateMany() method to update multiple documents in a collection at once.


db.collection.updateMany(
   <filter>,
   <update>,
   <options>
)
    
  • <filter>: Specifies the selection criteria for the update.
  • <update>: Specifies the modifications to apply.
  • <options>: Specifies additional options, such as upsert and arrayFilters.

For example, let's say we have a collection called "users" and we want to update the age of all users whose name is "John" to 30. We can use the following code:


db.users.updateMany(
   { name: "John" },
   { $set: { age: 30 } }
)
    

This will update the age field for all documents in the "users" collection where name is "John".

Using BulkWrite()

In addition to updateMany(), MongoDB provides the BulkWrite() method to perform multiple write operations at once, including updates, inserts, and deletes.

The BulkWrite() method takes an array of write operations as a parameter.


db.collection.bulkWrite( [
   <write operation 1>,
   <write operation 2>,
   ...
] )
    

For example, let's say we want to update the age of all users whose name is "John" to 30 and delete all users whose name is "Jane". We can use the following code:


db.users.bulkWrite( [
   { updateMany :
      {
         "filter" : { "name" : "John" },
         "update" : { "$set" : { "age" : 30 } }
      }
   },
   { deleteMany :
      {
         "filter" : { "name" : "Jane" },
      }
   }
] )
    

This will update the age field for all documents in the "users" collection where name is "John" and delete all documents where name is "Jane".

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe