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:
- Using the $set Operator with Multiple Indexes
- 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:
How to Update Multiple Array Elements in MongoDB?
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.