'Update different fields of multiple object based on IDs in array in mongoDb

For instance, there is a following document in collection:

{
  _id: 'doc1',
  teams: [{
    _id: '1',
    name: 'team 1',
    color: 'red',
  }, {
    _id: '2',
    name: 'team 2',
    color: 'green',
  }, {
    _id: '3',
    name: 'team 3',
    color: 'blue',
  },
...]
}

And there is a partial update for teams:

{
  teams: [{
    _id: '1',
    name: 'A - team',
  }, {
    _id: '3',
    color: 'green',
  }]
}

To update the single element in array I can use $ operator like so:

db.collection.findOneAndUpdate({_id: 'doc1', 'teams._id':'1'}, {$set: {'teams.$.name': 'A - team'}})

However, I need to update multiple elements and get the result, what would be the best way to do it? Is there something similar to $push and $pull operators which works within a single operation?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source