Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push to two separate arrays in one update call in mongodb

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!

like image 418
Jeff W Avatar asked Dec 21 '14 20:12

Jeff W


People also ask

How do I push an array into an array in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.

What is Upsert in MongoDB?

In MongoDB, upsert is a method that is used to insert and update the value in any operation. In other words, the MongoDB upsert method is a combination of insert and update (insert + update = upsert). By default, the upsert method's value is always false.


1 Answers

You can specify multiple fields to the $push operator

db.collection.update(
   { _id :1 }, 
   { $push : { array1 : "1",   array2 : "5" }}
)
like image 178
styvane Avatar answered Sep 22 '22 22:09

styvane