Push to two separate arrays in one update call in

2019-01-09 12:28发布

问题:

I am trying to update to update two separate arrays in a document with one update call. Is there a way to do this?

For example if I have a document like:

{
  _id:1,
  array1:[1],
  array2:[4]
}

right now i am doing this:

db.collection.update({_id:1},{$push:{array1:"2"}})
db.collection.update({_id:1},{$push:{array2:"5"}})

Is there a way to reduce this to just one call? I have tried just passing an array to push, i have tried multiple push statements in update object but those don't work. Thanks for your help with this!

回答1:

You can specify multiple fields to the $push operator

db.collection.update(
   { _id :1 }, 
   { $push : { array1 : "1",   array2 : "5" }}
)