![]() |
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?
Examples of How to Update Multiple Array Elements in MongoDBTo 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 Output: ![]() collection created Example 1: By using the “$set” and “$” positional operatorsLet’s Update the ‘Games’ array for the document where Name is ‘Makin’ to replace ‘Tennis’ with ‘Badminton’. db.members.updateOne( Output: { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Example 2: Updating Multiple Array Elements based on Array PositionLet’s Update the first two elements of the ‘Games’ array in documents where Country is ‘India’ to ‘Chess’ and ‘Volleyball’ respectively. db.members.updateMany( Output: { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Example 3: Updating Multiple Array Elements in all Documents based on the Array FilterLet’s Update all documents to replace all occurrences of ‘Tennis’ in the ‘Games’ array with ‘Swimming’. db.members.updateMany( Output: { "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }
Example 4: Updating Multiple Specific Array Elements using the $eleMatch operatorLet’s Update documents where Country is ‘India’ to replace occurrences of ‘Tennis’ or ‘Hockey’ in the ‘Games’ array with ‘Badminton’. db.members.updateMany( Output: { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
ConclusionOverall, 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. |
Reffered: https://www.geeksforgeeks.org
Databases |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |