Follow by Email

Update multiple Array Elements in MongoDB


Updating multiple arrays in a MongoDB document is released with 3.6 version.

With the release of MongoDB 3.6 updating multiple array elements can be done using filtered positional $[<identifier>]

The "arrayFilters" can be passed in the options for .update(), .updateOne(), .updateMany(), .findOneAndUpdate() or .bulkWrite() method specifies the conditions to match on the identifier given in the update statement. Any elements that match the condition given will be updated.

Below example for updating multiple array elements in a document, consider a collection employee :








  /* 1 */
 {
  "_id" : 1,
  "score" : [ 
   10, 
   70, 
   50
  ]
 }

 /* 2 */
 {
  "_id" : 2,
  "score" : [ 
   20, 
   50, 
   60
  ]
 }

 /* 3 */
 {
  "_id" : 3,
  "score" : [ 
   20, 
   60, 
   30
  ]
 }



Update query





  db.employee.update(
  { },
  { $set: { "score.$[element]" : 40 } },
  { multi: true,
  arrayFilters: [ { "element": { $gte: 30 } } ]
  }
   )