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!
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.
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.
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.
You can specify multiple fields to the $push
operator
db.collection.update(
{ _id :1 },
{ $push : { array1 : "1", array2 : "5" }}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With