Open In App

How to Update Multiple Array Elements in MongoDB?

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB, the popular NoSQL database, offers powerful features for manipulating data, including the ability to update multiple array elements within a document. Efficiently updating multiple elements in an array can be important in various scenarios, such as managing user preferences, and handling inventory quantities.

In this article, we will learn about How to Update Multiple Array Elements in MongoDB by understanding various methods along with the multiple examples and so on.

How to Update Multiple Array Elements in MongoDB?

Updating multiple array elements in MongoDB is a common requirement in database operations, often encountered in scenarios such as managing user preferences, tracking inventory, or processing historical data. MongoDB provides powerful methods to update multiple array elements within documents efficiently.

updateMany() method in MongoDB to update multiple array elements. Unlike traditional approaches, updateMany() allows us to perform bulk updates across multiple documents, improving performance and scalability.

However Below are the approaches that help us to Update Multiple Array Elements in MongoDB as follows:

  1. Using the $set Operator with Multiple Indexes
  2. Using the $map Operator with Aggregation

To understand How to to Update Multiple Array Elements in MongoDB we need a collection and some documents on which we will perform various queries. Here we will consider a collection called members which contains information like Name, Country, Age and Games of the members in various documents.

// Inserting example documents into the database
db.members.insertMany([
    { "Name": "Makin",
     "Country": "India",
     "Age": 26,
     "Games": ["Tennis", "Football"]
    },
    
    { "Name": "Dani", 
     "Country": "USA",
     "Age": 25, 
     "Games": ["Carroms", "Cricket"]
    },
    
    { "Name": "Carlin",
     "Country": "India",
     "Age": 24,
     "Games": ["Hockey", "Basketball"] 
    },
    
    { "Name": "Bobby", 
     "Country": "Dubai",
     "Age": 28, 
     "Games": ["Tennis", "Football"] 
    },
    
    { "Name": "Sundhar", 
     "Country": "Nepal",
     "Age": 27, 
     "Games": ["Tennis", "Baseball"]
    }
]);

Output:

membersCollection

collection created

1. Using the $set Operator with Multiple Indexes

The $set operator in MongoDB is used within update operations to set a specific field to a given value. It can be used to create a new field if it doesn’t exist or update an existing field with a new value.

Example 1:

Let’s create a MongoDB collection named ‘members’ and insert sample documents. Then, we’ll update the documents for members who’s Age greater than 26, from the collection.

// Updating elements of documents for members who are aged 26 or above
db.members.updateMany(
   { Age: { $gte: 26 } }, 
   { $set: { Age: 40 } }
);

// Displaying documents after the update
db.members.find();

Output:

Using-the-$set-Operator-with-Multiple-Indexes01

Updating Multiple Array Elements

Explanation: In the above output, we updated the documents in members who Age is greater than 26, from the collection.

Example 2:

Let’s Update the “Country” field in multiple documents of the “members” collection where the “Country” is currently set to “India” to “Sri Lanka“.

// Update documents where Country is "India" to "Sri Lanka"
db.members.updateMany(
   { Country: "India" }, 
   { $set: { Country: "Sri Lanka" } }
);

// Displaying documents after the update
db.members.find();

Output:

Using-the-$set-Operator-with-Multiple-Indexes02

Updating Multiple Array Elements

Explanation: In the above output, we updated the documents in members,where the country field India isupdated as srilanka from the collection.

2. Using the $map Operator with Aggregation

The $map operator in MongoDB is used within the aggregation framework to iterate over elements in an array and apply an expression to each element. It’s particularly useful for transforming or manipulating arrays within documents.

Example 1:

Let’s Multiply the “Age” field of each document in the “members” collection by 2 using the $addFields stage in an aggregation pipeline.

// Aggregation pipeline to update Age by multiplying each element by 2
db.members.aggregate([
    {
        $addFields: {
            Age: { $multiply: ["$Age", 2] } // Multiply each age by 2
        }
    }
]);

Output:

Using-the-$map-Operator-with-Aggregation01

Updating Multiple Array Elements

Explanation: In the above output, we updated the documents in members, where the Age fields are multiplied with 2, from the collection.

Example 2:

Let’s Update the “Country” field in all documents of the “members” collection. If the current value of “Country” is “India”, update it to “Washington”, otherwise, keep the current value.

// Aggregation pipeline to update Country from "India" to "Sri Lanka"
db.members.aggregate([
    {
        $addFields: {
            Country: {
                $cond: { 
                    if: { $eq: ["$Country", "India"] }, 
                    then: "Washington", 
                    else: "$Country" 
                }
            }
        }
    }
]);

Output:

Using-the-$map-Operator-with-Aggregation02

Updating Multiple Array Elements

Explanation: In the above output, we updated the documents in members, where the country contains india update it as washington, from the collection.

Conclusion

Overall, Updating multiple array elements in MongoDB is a powerful feature that can simple your database operations. By understanding these techniques discussed in article, you can efficiently manage and manipulate arrays within your MongoDB documents.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads