• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:10 mins read
You are currently viewing MongoDB Update Multiple Array Elements

By using the $ positional operator and the $set operator you can easily update the array elements in MongoDB including. Besides these there are various methods for updating arrays, In this article, we will cover all these including updating arrays based on array position and array filters.

Advertisements

Let’s use the collection shop with the multiple array elements, and see how to update these with examples.

#Collection Created
db.shop.insertMany([
      {
          "_id": 1,
          "product" : "Laptop" ,
          "price": [900, 500, 700],
          "color": ["Black", "White", "Grey"],
          "brand": [{"Apple": "Available", "Asus": "Not-Available"}]          
      },
       {
            "_id": 2,
          "product" : "Mobile" ,
          "price": [200, 600, 500],
          "color": ["White", "Silver", "Black"],
           "brand": [{"Apple": "Available", "Redmi": "Available"}]
       },
       {
          "_id": 3,
          "product" : "Airpods" ,
          "price": [100, 250, 350],
          "color": ["Black", "White"],
           "brand": [{"Apple": "Available", "Samsung": "Not-Available", "Redmi":"Available"}]
       }
  ])

1. By using the “$set” and “$” positional operators

You can use the $set operator along with the $ positional operator to update an array in MongoDB. Moreover, the $ operator is used to identify the index of the element you want to update. While the $set operator is used to set the new value for the element.

Here, we updated the Black to Dark Black in the color array field for all the documents. In addition, the $set operator specifies the value to be updated.

Furthermore, the $ operator identifies the index of the element, which will be automatically determined by MongoDB based on the matching criteria.


#$set and $ operator to update array elements
db.shop.updateMany(
    {color:"Black"},
    {$set:{"color.$":"Dark Black"}})

Finally, the output shows the updated array element:

MongoDB Update Array

Also, the updated documents output is displayed here:

MongoDB Update Array

However, we can also update the multiple array elements by specifying the conditional operator. Take account into the following example, where the price array elements are updated using the conditional operator. 

It must be remembered, when the price is greater than or equal to 200, then it will be modified with the new value of 550 by the $set operator.


#$set and $ operator to update multiple array elements
db.shop.updateMany(
   { "price": { $gte: 200 } },
   { $set: { "price.$": 550 } }
)

Finally, the modified price is yielded in the output.

However, the modified documents output is presented below:

2. Updating Multiple Array Elements based on Array Position

You can also use the $[] operator to update all of the components in an array when their positions in the array are known. All array elements are represented as placeholders by the $[] operator, enabling us to update every element at once.

Also, we updated the Redmi and Apple fields of all elements in the brand field of the document with the _id of 3. Moreover, the $[] operator here indicates that all elements in the array should be updated.


#$[] operator usage
db.shop.update(
   { _id: 3 },
   { $set: {
       "brand.$[].Redmi": "Limited Range",
       "brand.$[].Apple": "Not-Available"
     }
   }
)

Finally, the specified document results are generated with the modified elements of the array.

Update Array Elements

Following is the updated document output:

You can get more information about the $[] operator at the MongoDB offical website.

3. Updating Multiple Array Elements in all Documents based on the Array Filter

Furthermore, we can also update specific elements in an array based on criteria using the arrayFilters option in combination with the $[] operator. Moreover, we can define one or more criteria that must be satisfied before an element is updated using the arrayFilters option.

In the following case, the document whose array color element is White will be modified to the value Maroon. Thus, the arrayFilters option specifies the condition that must be matched for an element to be updated.


#$[] operator usage
db.shop.updateMany(
    {}, 
    { $set: {"color.$[element]":"Maroon"}},
    { arrayFilters: [{ element: "White" }]})

The results show the updated array elements for all the documents.

Also, cited below is the updated documents output:

MongoDB Update Array  Elements

4. Updating Multiple Specific Array Elements using the $eleMatch operator

The $elemMatch operator is an approach to update multiple specific elements in the favorites array. We can match the desired elements to update and then use the $set operator to update the fields. Here, we have another sample collection sports having an array of teams.


#$eleMatch Operator
db.sports.insert([{
  "_id": 1,
  "sports": "Football",
  "teams": [
    { "name": "Wolf", "color": "Brown", "score": 6 },
    { "name": "Tigers", "color": "Orange", "score": 3 },
    { "name": "Hybirds", "color": "Green", "score": 9 }
  ]
}])

Also, we have the query to update the score field of the Wolf and Tigers elements in the teams array to 10. Likewise, $[elem] allows us to use the arrayFilters option to specify which elements to update based on their properties.


#Using $set and arrayFilters option
db.sports.updateMany(
  { _id: 1, teams: { $elemMatch: { $or: [{ name: "Wolf" }, { name: "Tigers" }] } } },
  { $set: { "teams.$[elem].score": 10 } },
  { arrayFilters: [{ "elem.name": { $in: ["Wolf", "Tigers"] } }] }
)

The following output shows the modification.

Also, the updated document output is cited below:

MongoDB Update Array

More information on the $eleMatch operator can be found here.

5. Conclusion

In conclusion, MongoDB has a significant feature that lets us quickly and effectively update multiple array elements. Here, we have covered the basics of updating arrays in MongoDB including the use of the $ positional operator and the $set operator. Also, more advanced techniques for updating specific array elements based on various criteria have been discussed.

Related Articles