Skip to main content

How to Use updateMany() in MongoDB to Modify Multiple Documents

Learn how to use and optimize the performance of the updateMany() operator in MongoDB to update multiple documents in a single operation.
Jun 12, 2025  · 4 min read

When it comes to MongoDB, there might be scenarios where you want to update multiple documents with a single operation. While you could loop through documents and update them individually, updateMany offers a faster, more efficient solution.

In this short tutorial, we'll learn how to use the updateMany operator in MongoDB and optimize queries to achieve the best possible performance.

To build a strong foundation in MongoDB's data handling capabilities using Python, consider exploring the course on Introduction to MongoDB in Python.

Looking at a Practical Example of Updating Multiple MongoDB Documents

To illustrate this concept, let's use a practical example where you might want to update more than one document at a time.

Take the following data as our foundation for the example:

[
    { "name": "Nic Raboy", "title": "Master of Shenanigans", "salary": 50000, "last_raise_date": new Date("2013-06-01") },
    { "name": "Megan Grant", "title": "Word Wrangler", "salary": 125000, "last_raise_date": new Date("2020-12-01") },
    { "name": "Tony Kim", "title": "Alliance Czar", "salary": 80000, "last_raise_date": new Date("2025-02-01") },
];

In the above JSON, we have three employees at a fictional company. The company wants to give everyone a boost in compensation if they haven't received any salary adjustments for a certain time.

To update everyone who qualifies, we can make use of the updateMany operator in MongoDB. To accomplish our task, we might end up with a statement that looks like the following:

db.employees.updateMany(
    {
        "last_raise_date": {
            "$lte": new Date("2024-01-01")
        }
    },
    {
        "$mul": { "salary": 1.06 },
        "$set": { "last_raise_date": new Date() }
    }
);

So, what does the above updateMany operation do?

Taking a step back, the updateMany operator takes two parameters with an optional third parameter. 

  • The first parameter is an object representing the data we want to filter. 
  • The second parameter is the changes that we want to make to the results found in the filter. 
  • The optional third parameter could be { “upsert”: true }, which would insert a document if there were no matches.

With that in mind, we are first filtering for all documents where the last_raise_date is earlier than "2024-01-01". Looking back at our very basic dataset, we know we have two of the three documents matching:

[
    { "name": "Nic Raboy", "title": "Master of Shenanigans", "salary": 50000, "last_raise_date": new Date("2013-06-01") },
    { "name": "Megan Grant", "title": "Word Wrangler", "salary": 125000, "last_raise_date": new Date("2020-12-01") }
];

Two different changes will be made to the filtered documents based on the change criteria parameter.

"$mul": { "salary": 1.06 },

First, we're using the $mul operator to multiply one of our fields by a value. In our example, we want to give every qualifying employee a 6% increase in salary. This means we're simply multiplying the current value of the field by 1.06.

To help us document the salary adjustments while also preventing accidental increases in the future, we want to update the last_raise_date to the current date:

"$set": { "last_raise_date": new Date() }

If we were to run our updateMany operation again, nothing would happen because the last_raise_date found in the filter would no longer match any of our three documents.

The above is just an example, but your filter criteria could be much more complex, and likewise, what you plan to change could also be more complex, depending on your use case.

Boost the Performance of Your Update with a MongoDB Index

In our example, we were working with three small documents. Pretty much no matter what operation we throw at our collection, it will be fast because we won't be working with a whole lot. However, think of a production application where you're working with millions of documents or you’re frequently running the update operation.

If we tried to use the updateMany operator on millions of documents, it might take some time unless we had a proper index established for our filter criteria.

To create an index for our example, we can execute something like this:

db.employees.createIndex({ "last_raise_date": 1 });

You can validate that the updateMany operation is using our index by executing the following:

db.runCommand({
    "explain": {
        "update": "employees",
        "updates": [
            {
                "q": { 
                    "last_raise_date": { 
                        "$lte": new Date("2024-01-01") 
                    }
                },
                "u": {
                    "$mul": { "salary": 1.06 },
                    "$set": { "last_raise_date": new Date() }
                }
            }
        ]
    },
    "verbosity": "allPlansExecution"
});

In the results, if the inputStage is "IXSCAN," then you're using an index and maximizing your updateMany performance. If the inputStage is "COLLSCAN," then you're not using an index and may need to rethink how you're creating your index based on your filter criteria.

To clear up any confusion, we're using runCommand above to profile our operation of updating multiple documents. If you don't need any profiler information, stick with the much simpler and more elegant updateMany operation.

Conclusion

Updating multiple documents in a single operation in MongoDB is not a difficult task, as seen throughout the tutorial. 

Using the updateMany operator, we can define a filter criteria to match our documents against and then a change criteria with a list of changes to make. This updateMany operation can be further optimized by making sure you have a proper index that fits with your filter criteria.

If you’re new to non-relational databases, the Introduction to NoSQL course offers a helpful overview of concepts like document stores.

Become a Data Engineer

Prove your skills as a job-ready data engineer.
Fast-Track My Data Career

FAQs

What is the difference between updateOne and updateMany in MongoDB?

 updateOne modifies the first matching document, while updateMany updates all documents that meet the filter criteria. Choose based on the desired scope of change.

Can updateMany be used with upsert in MongoDB?

Yes, adding { upsert: true } as the third argument will insert a new document if no matches are found. However, it's more commonly used with updateOne.

What are some common use cases for updateMany?

It’s often used for batch updates like adjusting prices, modifying user statuses, or cleaning outdated fields in large datasets.

Does updateMany return any result data?

Yes, it returns an object with information such as matchedCount and modifiedCount, indicating how many documents were matched and updated.

What happens if no documents match the filter in updateMany?

If no documents match and upsert is not used, the operation completes with no changes. No error is thrown.

Is updateMany atomic in MongoDB?

No, it is not atomic across multiple documents. Each document update is atomic on its own but not collectively.

How can I test the performance of updateMany operations?

Use the explain() or runCommand({ explain: ... }) methods to see if your query uses an index or performs a collection scan.

Can I chain multiple update operators in updateMany?

Yes, MongoDB supports combining operators like $set, $inc, $mul, etc., in a single updateMany call.

What’s the impact of indexes on updateMany operations?

Indexes can drastically improve performance by reducing the number of scanned documents during filtering.

How do I undo an accidental updateMany operation?

You’d need to restore from a backup or log, as MongoDB doesn’t have built-in rollback for updateMany. Always test on staging and back up production data first.


Nic Raboy's photo
Author
Nic Raboy

Nic Raboy is a Developer Relations Lead at MongoDB where he leads a team of Python, Java, C#, and PHP developers who create awesome content to help developers be successful at including MongoDB in their projects. He has experience with Golang and JavaScript and often writes about many of his development adventures.

Topics

Learn more about MongoDB and databases with these courses!

Course

Introduction to Databases in Python

4 hr
98.8K
In this course, you'll learn the basics of relational databases and how to interact with them.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

What Is MongoDB? Key Concepts, Use Cases, and Best Practices

This guide explains MongoDB, how it works, why developers love it, and how to start using this flexible NoSQL database.
Karen Zhang's photo

Karen Zhang

15 min

Tutorial

How to Update Multiple Columns in SQL

Learn how to update multiple columns in SQL using a single query for improved efficiency. Explore practical advanced techniques and examples, including single row updates and multiple row updates.
Allan Ouko's photo

Allan Ouko

8 min

Tutorial

MongoDB find(): A Complete Beginner's Guide to Querying Data

This guide explains how to use the MongoDB find() method to query, filter, sort, and paginate data with real-world examples. Perfect for beginners and those transitioning from SQL.
Samuel Molling's photo

Samuel Molling

9 min

Tutorial

MongoDB Aggregation Pipeline Tutorial in Python with PyMongo

Explore MongoDB aggregation pipelines using PyMongo. Understand data flow, stages like $match, $project, $group, $lookup, and advanced patterns.
Bex Tuychiev's photo

Bex Tuychiev

15 min

Tutorial

Introduction to MongoDB and Python

In this tutorial, you'll learn how to integrate MongoDB with your Python applications.
Derrick Mwiti's photo

Derrick Mwiti

12 min

Tutorial

SELECTing Multiple Columns in SQL

Learn how to easily select multiple columns from a database table in SQL, or select all columns from a table in one simple query.
DataCamp Team's photo

DataCamp Team

4 min

See MoreSee More