Adeel Imran
Adeel Imran

Reputation: 13956

How to update multiple arrays in separate object

Hi let's say that I have these 3 objects in a collection

{
  id: 1,
  users: ['sam', 'john', 'lizy'],
  isActive: false,
}, {
  id: 2,
  users: ['sam', 'mathew', 'chandler'],
  isActive: false,
}, {
  id: 3,
  users: ['monica', 'rachel', 'sam'],
  isActive: false,
}

I want to update collection where id is 1 and 2. The only update I want it in the users array I want to replace "sam" with "superman"

Upvotes: 1

Views: 22

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

You basically want the positional $ operator as well as $in in order to match both documents:

db.getCollection('collection').updateMany(
  { "id": { "$in": [1,2] }, "users": "sam"  },
  { "$set": { "users.$": "superman" } }
)

Note that without the $in it's still going to update "sam" even though it's in a different array position.

The key part to working with the positional operator is that something needs to match the array "position", so we include "users": "sam" within the query conditions. This translates $ to be the "matched position" of the element in the array when the operation ( $set in this case ) is applied.

Note also .updateMany() is the modern driver equivalent to .update() with { "multi": true } always set to on.

Upvotes: 2

Related Questions