Salvador Dali
Salvador Dali

Reputation: 222511

mongodb push element into array of objects

I have a collection with a following schema:

{
  "_id" : ObjectId("4ee3ddc346b3b8880a000000"),
  ...
  "msgs" : [{
      "mid" : ObjectId("4ee3ddc346b3b8880a000000"),
      "deleted" : []
    },
    {
      "mid" : ObjectId("4ee3ddc346b3b8880a000100"),
      "deleted" : []
    }]
}

I want to do this query: for the specific _id insert into each "deleted" array an element

so after doing this query I will receive something like this:

{
  "_id" : ObjectId("4ee3ddc346b3b8880a000000"),
  ...
  "msgs" : [{
      "mid" : ObjectId("4ee3ddc346b3b8880a000000"),
      "deleted" : [2]
    },
    {
      "mid" : ObjectId("4ee3ddc346b3b8880a000100"),
      "deleted" : [2]
    }]
}

What I tried to do:

db.dialogs.update(
{ "_id" : ObjectId("4ee3ddc346b3b8880a000000")},
{$addToSet : {'msgs.$.deleted' : 2}}
)

the problem is that it only updating the first element element in the array, instead of all the elements

Any ideas?

Upvotes: 1

Views: 2961

Answers (1)

James Chen
James Chen

Reputation: 10874

Specify the multiple update option:

db.dialogs.update(
  { "_id" : ObjectId("4ee3ddc346b3b8880a000000")},
  {$addToSet : {'msgs.$.deleted' : 2}},
  false,
  true
)

The last parameter true tells mongodb to update all matching documents. (the third parameter tells mongodb not to do upset).

PS: the above assumes your original query and $ operation is correct, I didn't confirm that in MongoDB.

Upvotes: 1

Related Questions