Open In App

MongoDB updateMany() Method – db.Collection.updateMany()

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB updateMany method is a powerful feature used to update multiple documents in a collection that match a specified filter. This method allows developers to efficiently perform bulk update operations, reducing network overhead and improving performance

In this comprehensive guide, we will explore the updateMany() method in detail, including its syntax, behavior, options, and examples.

What is the updateMany() Method in MongoDB?

The MongoDB updateMany is used to update multiple documents in a collection that match a specified filter. It applies the specified modifications to every matching document in a single operation, making it a highly efficient tool for bulk updates. In this method, if the value of upsert is set to true for the sharded collection, then we must include the full shard key in the filter/selection criteria.

Key Features of updateMany():

  • Updates multiple documents based on the provided filter criteria.
  • Supports various options like upsert, writeConcern, and collation.
  • Can be used inside multi-document transactions.
  • Accepts aggregation pipelines for more complex updates.
  • Ensures atomicity for each document, maintaining data integrity.

Syntax:

db.collection.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, … ],
hint: <document|string>
}
)

Key Terms

  • filter: A query that matches the documents to update.
  • update: The modifications to apply. This can include update operators like $set, $unset, $inc, etc.
  • upsert (optional): If true, creates a new document if no documents match the filter. The default is false.
  • writeConcern (optional): A document expressing the write concern.
  • collation (optional): Specifies the collation to use for the operation.
  • arrayFilters (optional): An array of filter documents that determines which array elements to modify for an update operation on an array field.
  • hint (optional): The index to use for the query

Behavior of updateMany()

  • Bulk Updates: The MongoDB updateMany updates all documents that match the specified filter criteria. This method performs a bulk update operation, applying the specified update to each document that meets the filter conditions.
  • Efficient and Reliable: It provides the ability to update multiple documents in a single command, which can significantly improve performance and reduce network overhead compared to individual updates.
  • Flexible Options: The operation is atomic for each document, ensuring data integrity. MongoDB updateMany supports various options, including write concerns and collation, allowing for customized and reliable updates that adhere to localespecific rules and acknowledgment requirements from replica set members.

Examples of updateMany() in MongoDB

To understand MongoDB updateMany we need a collection called students on which we will perform various operations and queries.

Example 1: Update a Single Document

Let’s Update the age of the student named “aaksh” to 20 using MongoDB updateMany, run the following query:

Query:

db.student.updateMany({name: "aaksh"}, {$set:{age: 20}})

Output:

Update-single-document

Explanation:

Even though updateMany is designed for bulk updates, it can also update a single document if the filter matches only one document. In this case, only the document where name is “aaksh” will be updated.

Example 2: Update Multiple Documents

To set the “eligible” field to “true” for all students whose age is 18, use the following query:

Query:

db.student.updateMany({age:18},{$set:{eligible:"true"}})

Output:

Update-Multiple-Documents

Explanation:

The updateMany method applies the $set operator to all documents that match the filter { age: 18 }. This ensures that every student with an age of 18 will now have an eligible field added (or updated) with the value "true". This is an efficient way to update multiple documents in a single operation.

Example 3: Update with Upsert

Let’s Update all documents matching the condition to set “eligible” to false and create a new document if no match is found, use the following query:

Query:

db.student.updateMany({age: 18}, {$set: {eligible: false}}, {upsert: true})

Output:

Update-Multiple-Documents-with-Upsert

Explanation:

The upsert option ensures that if no documents match the filter { age: 18 }, a new document will be created with the specified values. This query updates all existing documents where age is 18, setting the eligible field to false, and if no such documents exist, it creates a new document with the age field set to 18 and eligible set to false. This combines update and insert operations efficiently.

Example 4: Update with Write Concern

To update the age of all students aged 18 to 20 with a write concern that requires majority acknowledgment, use the following query:

Query:

db.student.updateMany(
{ "age": 18 },
{ $set: { "age": 20 } },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
db.student.find().pretty()

Output:

{
"_id": ObjectId("600ebc010cf217478ba93570"),
"name": "aaksh",
"age": 15
}
{
"_id": ObjectId("600ebc010cf217478ba93571"),
"name": "nikhil",
"age": 20
}
{
"_id": ObjectId("600ebc010cf217478ba93572"),
"name": "vishal",
"age": 20
}

Explanation:

The writeConcern option specifies the level of acknowledgment required for the write operation. In this case, w: "majority" ensures that the update is acknowledged by the majority of replica set members, providing reliability. The wtimeout option sets a timeout of 5000 milliseconds to prevent indefinite waiting for acknowledgment

Example 5: Update with Collation

To update the age of all students aged 18 to 20 with a write concern and collation settings for locale-specific rules, use the following query:

Query:

db.student.updateMany(
{ "age": 18 },
{ $set: { "age": 20 } },
{
writeConcern: { w: "majority", wtimeout: 5000 },
collation: { locale: "en", strength: 2 }
}
)

db.student.find().pretty()

Output:

{
"_id": ObjectId("600ebc010cf217478ba93570"),
"name": "aaksh",
"age": 15
}
{
"_id": ObjectId("600ebc010cf217478ba93571"),
"name": "nikhil",
"age": 20
}
{
"_id": ObjectId("600ebc010cf217478ba93572"),
"name": "vishal",
"age": 20
}

Explanation:

This query updates all documents where age is 18, changing it to 20, while adhering to the specified collation and acknowledgment rules. This ensures that updates are handled according to locale-specific settings.

Important Points About updateMany()

  1. Bulk Updates: Efficiently updates multiple documents in a single operation.
  2. Atomicity: Ensures that each document is updated atomically.
  3. Flexible Options: Provides advanced features like upsert, writeConcern, and collation.
  4. Supports Aggregation Pipelines: Can handle complex updates using aggregation frameworks.
  5. Index Optimization: Using the hint option ensures queries are optimized with the appropriate index.

Conclusion

The updateMany() method in MongoDB is a highly efficient tool for performing bulk updates on multiple documents. It offers flexibility with options like upsert, writeConcern, and collation, allowing developers to customize updates based on their needs. By mastering the updateMany() method, you can handle large-scale updates while ensuring data integrity and performance. Whether you are updating a few documents or applying changes across an entire dataset, updateMany() is a critical feature for managing MongoDB collections effectively.



Next Article

Similar Reads