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
How to Remove Array Elements by Index in MongoDB
In MongoDB, arrays are a flexible data structure that allows storing multiple values within a single document field. Occasionally, we may need to remove specific elements from an array based on their index. In this article, we'll explore how to remove array elements by index in MongoDB by providing
5 min read
How to Update Objects in a Document's Array in MongoDB?
In the area of MongoDB, managing a database with a large collection of documents can be challenging especially when it comes to updating specific objects within arrays of nested objects. This scenario is common in NoSQL databases like MongoDB. In this article, weâll explore some methods for updating
5 min read
How to Update Deeply Nested Array in MongoDB/ Mongoose ?
In MongoDB/Mongoose, updating deeply nested arrays can be challenging due to the nested structure. This article will explore various approaches to update deeply nested arrays efficiently using both MongoDB queries and Mongoose methods. Explaining each approach one by one below: Table of Content Usin
2 min read
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _i
3 min read
How to Update the First Object in an Array in MongoDB
MongoDB, a popular NoSQL database, offers powerful features for handling complex data structures. One common scenario is updating specific elements within arrays stored in documents. In this guide, we'll focus on updating the first object in an array within a MongoDB document. We'll cover the concep
3 min read
How to delete single and multiple documents in MongoDB using node.js ?
MongoDB, the most popular NoSQL database is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to Filter Array in Subdocument with MongoDB?
In MongoDB, working with arrays within subdocuments is a common requirement in many applications. Filtering and manipulating arrays efficiently can significantly enhance the flexibility and enhance our queries. In this article, we'll explore how to filter arrays within subdocuments in MongoDB by cov
5 min read
How to push data in a MongoDB document ?
The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collectio
2 min read
How to insert single and multiple documents in Mongodb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read