bssyy78
bssyy78

Reputation: 349

node mongo : update multiple arrays at same time

I have the following document :

{
  name:"myDoc",
  array1:['a','b'],
  array2:['a','b'],
  array3:['a','b']
}

I would like to add in the same update operation, the value "c" to the 3 arrays. I know how to do it with 3 separate steps :

db.collection('myCollection').updateMany(
{name:'myDoc'},
  {$addToSet: { array1:"c" }}
)

and do that 3 times, but I want to know if its possible to do the 3 additions in one single update.

thanks

Upvotes: 0

Views: 45

Answers (1)

eol
eol

Reputation: 24565

Just specify all sets you want to update:

db.collection('myCollection')
  .updateMany(
     {name:'myDoc'},
     {$addToSet: { 
          array1:"c",  
          array2:"c",
          array3:"c" }
})

Example on mongoplayground: https://mongoplayground.net/p/yHqzi_lEaA0

Upvotes: 2

Related Questions