How to Update Multiple Array Elements in MongoDB?
Last Updated :
10 Jul, 2024
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.
Examples of How to Update Multiple Array Elements in MongoDB
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:
collection createdExample 1: By using the “$set” and “$” positional operators
Let's Update the 'Games' array for the document where Name is 'Makin' to replace 'Tennis' with 'Badminton'.
db.members.updateOne(
{ Name: 'Makin' },
{ $set: { 'Games.$[element]': 'Badminton' } },
{ arrayFilters: [ { 'element': 'Tennis' } ] }
)
Output:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Example 2: Updating Multiple Array Elements based on Array Position
Let's Update the first two elements of the 'Games' array in documents where Country is 'India' to 'Chess' and 'Volleyball' respectively.
db.members.updateMany(
{ Country: 'India' },
{ $set: { 'Games.0': 'Chess', 'Games.1': 'Volleyball' } }
)
Output:
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Example 3: Updating Multiple Array Elements in all Documents based on the Array Filter
Let's Update all documents to replace all occurrences of 'Tennis' in the 'Games' array with 'Swimming'.
db.members.updateMany(
{},
{ $set: { 'Games.$[element]': 'Swimming' } },
{ arrayFilters: [ { 'element': 'Tennis' } ] }
)
Output:
{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }
Example 4: Updating Multiple Specific Array Elements using the $eleMatch operator
Let's Update documents where Country is 'India' to replace occurrences of 'Tennis' or 'Hockey' in the 'Games' array with 'Badminton'.
db.members.updateMany(
{ Country: 'India' },
{ $set: { 'Games.$[element]': 'Badminton' } },
{ arrayFilters: [ { 'element': { $in: ['Tennis', 'Hockey'] } } ] }
)
Output:
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
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.
Similar Reads
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases. In this
11 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
ACID Properties in DBMS
In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Introduction of DBMS (Database Management System)
A Database Management System (DBMS) is a software solution designed to efficiently manage, organize, and retrieve data in a structured manner. It serves as a critical component in modern computing, enabling organizations to store, manipulate, and secure their data effectively. From small application
8 min read