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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

incorrect. What he wants here is to update several elements of a single document. Not all matching documents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.