Updating Multiple Documents in MongoDB: The updateMany() Method
Learn how to efficiently modify multiple documents in MongoDB collections using the updateMany() method. This guide will cover the various update operators and techniques, allowing you to perform bulk updates on your data. Understand the benefits of using updateMany() over updateOne() for efficient data modification.
MongoDB: Update Multiple Documents using updateMany()
MongoDB provides two primary methods to update documents in a collection:
db.collection.updateOne()
- Modifies a single document.db.collection.updateMany()
- Modifies multiple documents.
In most cases, updateMany()
is preferred over updateOne()
when you need to update multiple documents.
Syntax
The syntax for updateMany()
is:
Syntax
db.collection.updateMany(filter, update, options)
Parameters:
filter
: The selection criteria for the update, similar to thefind()
method.update
: A document or pipeline that contains modifications to apply.options
: Optional. Includes options for update behavior such asupsert
,writeConcern
,collation
, etc.
Sample Data
Insert the following documents into the employees
collection:
Insert Sample Data
db.employees.insertMany([
{ _id: 1, firstName: "John", lastName: "King", email: "john.king@abc.com", salary: 5000 },
{ _id: 2, firstName: "Sachin", lastName: "T", email: "sachin.t@abc.com", salary: 8000 },
{ _id: 3, firstName: "James", lastName: "Bond", email: "jamesb@abc.com", salary: 7500 },
{ _id: 4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 7000 },
{ _id: 5, firstName: "Kapil", lastName: "D", email: "kapil.d@abc.com", salary: 4500 },
{ _id: 6, firstName: "Amitabh", lastName: "B", email: "amitabh.b@abc.com", salary: 7000 }
])
Examples
1. **Update Matching Documents**
Update the salary
field for all documents where salary
is 7000:
Example: Update Salary
db.employees.updateMany({ salary: 7000 }, { $set: { salary: 8500 } })
Output:
{ acknowledged: true, insertedId: null, matchedCount: 2, modifiedCount: 2, upsertedCount: 0 }
Check the updated documents:
Check Updated Documents
db.employees.find()
Output:
[ { _id: 1, firstName: 'John', lastName: 'King', email: 'john.king@abc.com', salary: 5000 }, { _id: 2, firstName: 'Sachin', lastName: 'T', email: 'sachin.t@abc.com', salary: 8000 }, { _id: 3, firstName: 'James', lastName: 'Bond', email: 'jamesb@abc.com', salary: 7500 }, { _id: 4, firstName: 'Steve', lastName: 'J', email: 'steve.j@abc.com', salary: 8500 }, { _id: 5, firstName: 'Kapil', lastName: 'D', email: 'kapil.d@abc.com', salary: 4500 }, { _id: 6, firstName: 'Amitabh', lastName: 'B', email: 'amitabh.b@abc.com', salary: 8500 } ]
2. **Add a New Field**
Add the location
field to documents with firstName: "Steve"
:
Example: Add Location Field
db.employees.updateMany({ firstName: "Steve" }, { $set: { location: "USA" } })
Output:
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
Check the updated document:
Check Updated Document
db.employees.find({ firstName: "Steve" })
Output:
{ _id: 4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 8500, location: "USA" }
3. **Update All Documents**
Add the location
field to all documents:
Example: Update All Documents
db.employees.updateMany({}, { $set: { location: "USA" } })
Output:
{ acknowledged: true, insertedId: null, matchedCount: 6, modifiedCount: 6, upsertedCount: 0 }
4. **Use the $inc Operator**
Increase the salary
by 500 for documents where salary
is 8500:
Example: $inc Operator
db.employees.updateMany({ salary: 8500 }, { $inc: { salary: 500 } })
Output:
{ acknowledged: true, insertedId: null, matchedCount: 2, modifiedCount: 2, upsertedCount: 0 }
5. **Update Multiple Fields**
Update the email
and lastName
fields for the document with _id: 2
:
Example: Update Multiple Fields
db.employees.updateMany({_id: 2}, { $set: { lastName: "Tendulkar", email: "sachin.tendulkar@abc.com" } })
Output:
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
Check the updated document:
Check Updated Document
db.employees.find({_id: 2})
Output:
{ _id: 2, firstName: "Sachin", lastName: "Tendulkar", email: "sachin.tendulkar@abc.com", salary: 8000 }
6. **Upsert - Add if Not Exist**
Add a new document if no document matches the filter:
Example: Upsert
db.employees.updateMany({ firstName: "Heer" }, { $set: { lastName: "Patel", salary: 2000 } }, { upsert: true })
Output:
{ acknowledged: true, insertedId: ObjectId("6172a2e9ce7d5ca09d6ab082"), matchedCount: 0, modifiedCount: 0, upsertedCount: 1 }
Update Operators
Here are some common update operators you can use with updateOne()
and updateMany()
:
Method | Description |
---|---|
$currentDate |
Sets the value of a field to the current date, either as a Date or a Timestamp. |
$inc |
Increments the value of the field by the specified amount. |
$min |
Only updates the field if the specified value is less than the existing field value. |
$max |
Only updates the field if the specified value is greater than the existing field value. |
$mul |
Multiplies the value of the field by the specified amount. |
$rename |
Renames a field. |
$set |
Sets the value of a field in a document. |
$setOnInsert |
Sets the value of a field if an update results in an insert of a document. Has no effect on updates that modify existing documents. |
$unset |
Removes the specified field from a document. |
For more details, refer to the MongoDB Update Operators documentation.