Sling Academy
Home/MongoDB/MongoDB db.collection.updateMany() method (with examples)

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

Last updated: February 03, 2024

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.

Next Article: MongoDB: Is there something like ‘NOT NULL’ constraint in SQL?

Previous Article: MongoDB db.collection.updateOne() method (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)