hamed hamed
hamed hamed

Reputation: 81

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] }

Upvotes: 8

Views: 30987

Answers (5)

krekto
krekto

Reputation: 1487

$pushAll
Deprecated since version 2.4: Use the $push operator with $each instead.

The $pushAll operator appends the specified values to an array.

The $pushAll operator has the form:

{ $pushAll: { <field>: [ <value1>, <value2>, ... ] } }

If you specify a single value, $pushAll will behave as $push.

Upvotes: 0

TMS
TMS

Reputation: 311

the simplest approach is by using a conventional update operation

  db.urColl.update(
    { x: "h" },
    { $push: { arr: { $each: [6,8] } } },
    { multi: true }
  );`

Upvotes: 2

john_science
john_science

Reputation: 6561

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.

Upvotes: 8

Adam Comerford
Adam Comerford

Reputation: 21692

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

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

Upvotes: 11

Nate Ferrero
Nate Ferrero

Reputation: 1458

If you want to update multiple records, it's important to pass true as the 4th argument to the update function:

db.test.update( {"name": "x"}, {"$pushAll": {"arr": [1, 2, 3]}}, false, true)

Per the MongoDB shell syntax for update():

db.collection.update( criteria, objNew, upsert, multi )
  • upsert - if the record(s) do not exist, insert one. Upsert only inserts a single document
  • mutli - indicates if all documents matching criteria should be updated rather than just one

Upvotes: 1

Related Questions