Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Update (Insert a List of Item to an Array)

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] }
like image 955
hamed hamed Avatar asked Apr 30 '12 12:04

hamed hamed


People also ask

How do I add elements to an array in MongoDB?

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.

How do I update an entire array in MongoDB?

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.

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.


2 Answers

I think what you are looking for is the $pushAll operator. Take a look here:

http://docs.mongodb.org/manual/reference/operator/pushAll/#pushall

like image 117
Adam Comerford Avatar answered Nov 16 '22 04:11

Adam Comerford


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.

like image 39
john_science Avatar answered Nov 16 '22 04:11

john_science