Answer a question

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.

Answers

To push data into array based on condition you have to use $ne in your query.

  var data = {
      "id": 3.0,
      "text": "bllllllll"
    }

suppose you want to update data into array if the id is not in that array.

db.getCollection('local').update({
    _id: ObjectId("591d6d2091b1fda9dcb6ef69"),
    "messages.id":{$ne: data.id}
    },{$push:{messages: data}})

$ne match that if data.id is present in array then it ignore the update otherwise push the data into array.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐