Conditional push to the array in Mongodb

Viewed 3878

I have a collection of documents with the "messages" array field:

{
   "id": 2,
   "messages": [
      {
         "id": 1,
         "text": "foo"
      },
      {
         "id": 2,
         "text": "bar"
      }
   ]
}

I want to update documents: add a new "message" document to the "messages" field only if "messages" doesn't contain a document with such id. For example:

{
  "id": 2,
  "text": "bllllllll"
}

should not be added

{
  "id": 3,
  "text": "foo"
}

should be added

How can I do conditional append? I know that I can filter documents in the Find part via $elemMatch operator, but it will only work for Update, with Upsert it will not work anymore.

2 Answers
Related