将数组的最后一个元素的字段与父文档的字段进行比较

时间:2019-03-11 02:23:11

标签: mongodb mongodb-query aggregation-framework

我必须将父文档的嵌入字段与也是父文档一部分的最后一个文档的嵌入字段(在数组内部)进行比较,并在两个字段不匹配时返回文档的externalIds

供参考,以下是图像:
[包含数组的实际元数据] [1]
[这是另一个包含该字段的图像] [2]

因此,在第二张图片中,我实际上只希望将最后一个修订版本(即,修订版本数组中的最后一个文档)与父文档进行比较,并且需要与之比较的字段是metadata.formData.mergeStatus.status
我希望那些文档_id的数组中存在的最后一个文档的字段与其父文档的相应字段不同(如果存在修订版数组的话)。

我是mongodb的新手,并且第一次请求stackoverflow,所以如果您发现它愚蠢,请原谅,但这是我的尝试。

db.document.aggregate([
    { $match: { $and: [
        { spaceId: 3007 },
        { revisions: { $exists: true, $not: { $size: 0 } } }
    ] } },
    { $project:
        { _id: 1,
        spaceId:1,
        externalId:1,
        revisions: { $cond: {
            if: { $isArray: "$revisions" },
            then: { $size: "$revisions" },
            else: "NA" } },
        last: { $arrayElemAt: [ "$revisions", -1 ] },
        difference: { $ne: [
            "last.metadata.formData.mergeStatus.status", 
            "metadata.formData.mergeStatus.status" ] }
        }
    }
]); 

The above suggestion really helps however i am confused for below scenario,
so the metadata field contains elementsData and inside of that is another embedded object signature, which has two string fields 
1.userSignatureDate(String)
2.userSignatureText(String)
so when i have applied above logic to compare the *userSignatureDate* of parent metadata with respective field in last document of  the revisions array.it is not giving actual results.
here is the image for the code that i had written and the sample metadata Structure .[enter image description here][3][enter image description here][4]


  [1]: https://i.stack.imgur.com/rsrKv.png
  [2]: https://i.stack.imgur.com/y6wsp.png
  [3]: https://i.stack.imgur.com/398I8.png
  [4]: https://i.stack.imgur.com/PYUAL.png

1 个答案:

答案 0 :(得分:0)

尝试类似的事情

db.getCollection('test').aggregate([
{$project:
      {
          status: "$metadata.formData.mergeStatus.status", 
          last_revisions: { $arrayElemAt: [ "$revisions", -1 ] }
      }},
{$project:
    {
        matched:{
            $eq:[
            "$status",
            "$last_revisions.metadata.formData.mergeStatus.status"
            ]}
       }}
])