MongoDB updateMany

While working with MongoDB, you also get some advantages to updating the already existing documents. Updating in MongoDB can be done in 3 different ways (updateOne(), updateMany() and replaceOne()). Here, in this article, you are going to see updateMany() in detail.

updateMany() in MongoDB is used to update all the document that satisfies the given parameters.

Syntax

updateMany(filter, data, options)
  1. filters parameter is used to set the criteria for updating the documents.
  2. data parameter is used to decide how the data that satisfies the parameter will be edited.
  3. options parameter includes upsert, collation, writeConcern, and other options that we are going to discuss later.

Moving ahead, let's understand the concept of udpadeMany() with the help of an example:

Example

You have some documents in edatabase collection as shown below:

mongoDB updateMany

NOTE: There are 2 document that contain salary of less than 40000.

Now, you need to update all those documents that contain salary less than 40000. You need to given the incrementation of 5000 to those employees. The same process can be followed using the updateMany() command in MongoDB. Follow the code to perform the task:

db.edatabase.updateMany({Salary:{$lt: 40000}},{$inc:{Salary: 5000}})

Output

mongoDB updateMany

Now, checking the data after updating, you will find that all the documents that contains salary as less than 40000, will be incremented by 5000. Follow the image pasted below that displays the values in documents after updating:

mongoDB updateMany