MongoDB db.collection.updateMany() method (with examples)

Updated: February 3, 2024 By: Guest Contributor Post a comment

Overview

Welcome to this in-depth guide about using the MongoDB db.collection.updateMany() method. In MongoDB, updating documents within your collections is a common task, and mastering the updateMany() method can significantly improve your database management capabilities. This method allows you to update multiple documents within a collection that match a specified filter. Throughout this tutorial, we will explore various examples of how to use updateMany(), escalating from simple to more advanced use cases.

Before delving into the examples, it’s essential to grasp the syntax of the updateMany() method:

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

The updateMany() method accepts a filter object to determine which documents to update, an update object to specify the changes, and an optional options object for additional specifications such as upsert behavior, write concern, and so forth.

Basic Example: Updating Multiple Documents

db.products.updateMany(
    { category: "electronics" },
    { $set: { stock: 100 } }
)

This code updates the stock of all products in the “electronics” category to 100. The method looks for all documents matching the filter and applies the specified update.

Incrementing Fields in Multiple Documents

db.products.updateMany(
    { category: "books" },
    { $inc: { quantity: 2 } }
)

This example demonstrates how to increment the quantity field of all documents in the “books” category by 2. It showcases the power of the $inc operator in updating numerical values across multiple documents.

Adding Elements to an Array in Multiple Documents

db.products.updateMany(
    { tags: { $in: ["bestseller"] } },
    { $push: { tags: "discounted" } }
)

In this example, we add a new tag, “discounted”, to all products that already include the “bestseller” tag. The $push operator makes it easy to append values to an array field in multiple documents.

Conditional Updates with $set and $addToSet

db.products.updateMany(
    { stock: { $lt: 20 } },
    { $set: { status: "low stock" }, $addToSet: { tags: "restock" } }
)

This snippet targets products with stock levels below 20, updating their status to “low stock” and ensuring the tag “restock” is added without duplicates, demonstrating conditional updates and the use of $addToSet for managing array fields.

Updating Nested Fields

db.products.updateMany(
    { "details.manufacturer": "TechCorp" },
    { $set: { "details.shippingCost": 0 } }
)

Here, we perform an update on nested fields by specifying the path to the nested field. This affects all products manufactured by “TechCorp”, setting their shipping cost to 0. It’s a practical example of modifying properties in nested objects.

Using Upsert

db.products.updateMany(
    { item: "newItem" },
    { $set: { stock: 10, description: "Brand new item" } },
    { upsert: true}
)

This operation attempts to update documents matching the filter ({ item: “newItem” }). If no documents match, a new document is created because the upsert option is set to true. It’s a useful technique for ensuring a document exists without making a separate query to check beforehand.

Advanced: Applying Conditional Operations with arrayFilters

db.products.updateMany(
    {},
    { $set: { "details.$.price": 99 } },
    { arrayFilters: [{ "details.price": { $gt: 100 } }] }
)

This complex example applies a condition within an array of documents. It targets the price field within the details array, updating only those prices greater than 100 to 99. This demonstrates arrayFilters‘s role in applying updates selectively within arrays.

Conclusion

Throughout this guide, we’ve explored various use cases and examples of the db.collection.updateMany() method in MongoDB. Starting from the basics and progressing to complex scenarios, these examples demonstrate the flexibility and power of MongoDB in managing document updates at scale. By understanding and applying these techniques, developers can efficiently manipulate data to meet their application’s needs.