I want to add several items to arrays of several rows in Mongo. How can I do this?
I want to start with this:
{'x': 'h', arr: [1,2,3] }
{'x': 'h', arr: [1,3] }
and add the array [6,8], where the x is equal to 'h':
{'x': 'h', arr: [1,2,3,6,8] }
{'x': 'h', arr: [1,6,8] }
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
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.
I think what you are looking for is the $pushAll operator. Take a look here:
http://docs.mongodb.org/manual/reference/operator/pushAll/#pushall
If you have a MongoDB collection named yourCollection
and a record with the name x
, you would update the subarray with something like this:
db.test.update( {"name":"x"}, {"$pushAll" : {arr : [1, 2, 3]}} )
The important keyword here is $pushAll. You can use it to add items to arrays inside of a single record attribute.
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