Upsert mongo array of object with condition

喜夏-厌秋 提交于 2019-12-24 07:42:04

问题


I have a collection with some documents and each document has ha list of objects representing a temporal interval in epoch with a keyword. I want to update the final value of the interval of each object in the right document where the ending value is greater than a value. If nothing can be updated I want to insert a new interval with both start and end as the new value and with the keyword used in the query.

I'm using nifi to perform this task and the update block, with upsert enabled. I can use aggregation too but it should be possible to just do it with an upsert.

This is what I have in place right now

QUERY
{
    "_id":"docid",
    "thearray.keyword": "red",
    "thearray.end": {$gte :minUpdatable}
}

and this as the update body:

UPDATE BODY
{
      "thearray.$[].end": valueToUpdate,
      "$setOnInsert":{"$push": {"thearray":{"keyword":"red","start":valueToUpdate,"end":valueToUpdate}}}
    }
}

This is the document data structure: INITITAL STATUS

{
  _id:"docid",
  otherInfo:"",
  thearray:[
    {keyword:"red",start:8,end:15},
    {keyword:"blue",start:8,end:15},
    {keyword:"red",start:8,end:9},
    {keyword:"red",start:9,end:16},
    ...
  ]
}

EXAMPLE 1: In this situation, from initial status, updating with "docid" as the document, "red" as keyword, 12 as lower possible end value to update (minUpdatable) and 22 as the value to set the document should become something like:

{
  _id:"docid",
  otherInfo:"",
  thearray:[
    {keyword:"red",start:8,end:22},
    {keyword:"blue",start:8,end:15},
    {keyword:"red",start:8,end:9},
    {keyword:"red",start:9,end:22},
    ...
  ]
}

EXAMPLE 2: In the same situation, from initial status, updating with with "docid" as the document, "red" as keyword, 33 as lower possible end value to update and 39 as the value to set the document should result in something like (or any query that result in the impossibility to update) :

{
  _id:"docid",
  otherInfo:"",
  thearray:[
    {keyword:"red",start:8,end:15},
    {keyword:"blue",start:8,end:15},
    {keyword:"red",start:8,end:9},
    {keyword:"red",start:9,end:16},
    ...,
    {keyword:"red",start:33,end:33}
  ]
}

来源:https://stackoverflow.com/questions/57587116/upsert-mongo-array-of-object-with-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!