加入Mongo的Same Collection

时间:2019-05-08 19:35:25

标签: mongodb aggregate

下面是样本收集文档记录,我希望将相同的收集与不同的子数组元素连接起来。

样品采集记录:

    {
      "_id": "052dc2aa-043b-4cd7-a3f2-f3fe6540ae52",
      "Details": [
        {
          "Id": "104b0bb1-d4a5-469b-b1fd-b4822e96dcb0",
          "Number": "12345",
          "Percentages": [
            {
              "Code": "55555",
              "Percentage": "45"
            },
            {
              "Code": "55333",
              "Percentage": "50"
            }
          ]
        },
        {
          "Id": "104b0bb1-d4a5-469b-b1fd-b4822e96dcb0",
          "Number": "55555",
          "Percentages": [
            {
              "Code": "55555",
              "Percentage": "45"
            }
          ]
        }
      ],
      "Payments": [
        {
          "Id": "61ee1a6f-3334-4f33-ab6c-51c646b75c41",
          "Number": "12345"
        }
      ]
    }

我想获取具有匹配条件的 Percentages 数组的mongo Pipeline查询,其 Details.Number Payment.Number 应该为相同

结果:

"Percentages": [
        {
          "Code": "55555",
          "Percentage": "45"
        },
        {
          "Code": "55333",
          "Percentage": "50"
        }]

如何通过使用聚合将相同集合的子元素合并来带来结果?

1 个答案:

答案 0 :(得分:1)

以下查询可满足您的需求:

db.collection.aggregate([
    {$unwind : "$Details"}, 
    {$unwind : "$Details.Percentages"}, 
    {$unwind : "$Payments"},            // $unwind all your arrays
    {
        $addFields : {   //This include new `isMatch` field, which is gonna be true, only if Details.Number = Payment.Number
            "isMatch" : {$cond: { if: { $eq: [ "$Details.Number", "$Payments.Number" ] }, then: true, else: false }}
        }
    },
    {
        $match : {   // This ignores all others, for which Details.Number != Payment.Number
            "isMatch" : true
        }
    },
    {
        $group : { // This will return only the Percentage objects
            _id : null, 
            "Percentages" : {$push : "$Details.Percentages"}
        }
    },
    {
        $project : { // To ignore "_id" field
            _id : 0, 
            "Percentages" : 1
        }
    }
])

结果:

{
    "Percentages" : [ 
        {
            "Code" : "55555",
            "Percentage" : "45"
        }, 
        {
            "Code" : "55333",
            "Percentage" : "50"
        }
    ]
}

希望这会有所帮助!