So far, we have learned how to insert and update individual documents in a collection, but what if we want to update multiple documents simultaneously? This is where the MongoDB .updateMany()
method comes in handy.
The .updateMany()
method allows us to update all documents that satisfy a condition. The .updateMany()
method looks and behaves similarly to .updateOne()
, but instead of updating the first matching document, it updates all matching documents:
Let’s examine its syntax:
db.<collection>.updateMany( <filter>, <update>, <options> );
Like before, we have three main parameters:
filter
: The selection criteria for the update.update
: The modifications to apply.options
: Other options that could be applied, such asupsert
.
Let’s see how we can apply the method to an example. Suppose a company sets a minimum salary for all employees. We want to update all employees with a salary of $75,000 to the new minimum of $80,000. Here is what our collection of employees
might look like:
{ _id: ObjectId(...), name: "Rose Nyland", department: "Information Technology", salary: 75000 }, { _id: ObjectId(...), name: "Dorothy Zbornak", department: "Human Resources", salary: 75000 }, { _id: ObjectId(...), name: "Sophia Petrillo", department: "Human Resources", salary: 75000 }, { _id: ObjectId(...), name: "Blanche Devereaux", department: "Sales", salary: 80000 }
We can use .updateMany()
to target all employees with the same salary in order to increase it:
db.employees.updateMany( { salary: 75000 }, { $set: { salary: 80000 }} )
In the above example, we’re using the salary as the filter criteria: { salary: 75000}
. This targets any document with the salary set to 75000
. We can then use the second parameter (via the $set
operator) to update the specified fields in those documents. The collection would now look like this:
{ _id: ObjectId(...), name: "Rose Nyland", department: "Information Technology", salary: 80000 }, { _id: ObjectId(...), name: "Dorothy Zbornak", department: "Human Resources", salary: 80000 }, { _id: ObjectId(...), name: "Sophia Petrillo", department: "Human Resources", salary: 80000 }, { _id: ObjectId(...), name: "Blanche Devereaux", department: "Sales", salary: 80000 }
Notice how all employees with the salary
of 75000
had their salary increased to 80000
while the employee whose salary
was already 80000
stayed the same.
Let’s jump back into the restaurants
database to practice using the updateMany()
method to update multiple documents simultaneously.
Instructions
When inserting the information regarding the boroughs for the restaurant collection, there was a mixup between "Bronx"
and "Staten Island"
.
Connect to the restaurants
database. Then, using the listingsAndReviews
collection, update all the documents that have the borough
field as "Bronx"
to be "Staten Island"
instead.
Query the database for all the documents with the borough of "Staten Island"
to see the updated documents.