1

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?

TJD
  • 11,800
  • 1
  • 26
  • 34
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 1
    Possible duplicate of : http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb – DhruvPathak Dec 11 '11 at 19:24

1 Answers1

1

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.

James Chen
  • 10,794
  • 1
  • 41
  • 38