MongoDB - 在 $lookup 管道内匹配键匹配不起作用

MongoDB - Match inside $lookup pipeline for key matching not working

我卡在了 MongoDB 查询中。我有两个 collections.

计划 Collection:

{
    planName: 'TV1',
    planFeatures: {
        'AA1': true,
        'AA2 : false',
        'AA3': true,
        'AA4': true,
        'AA5': false
    }
}, {
    planName: 'TV2',
    planFeatures: {
        'AA1': true,
        'AA2 : false',
        'AA3': false,
        'AA4': true,
        'AA5': false
    }
}, ..........

planFeatures Collection

{
    key: 'AA1',
    label: 'ALPHA',
}, {
    key: 'AA2',
    label: 'BETA'
}, ..........

我正在尝试聚合 2 collections,这样计划 collections 中 planFeatures 字段的 key Name 应该等于planFeatures 的关键字段 collections 例如(plans.planFeatures 的键名)==(planFeatures.key) AA1 == AA1

PaymentPlanFeatures.aggregate([    
            {
                $lookup: {
                    from: 'plans',
                    let: { 'kkey': '$key'},
                    pipeline: [
                        { $set: { 'planFeatures5': { '$objectToArray': '$planFeatures' }}},
                        {
                            $match: {
                                $expr: {
                                    $eq: [
                                       '$planFeatures5.k', '$$kkey'
                                    ]
                                }
                            }
                        }
                    ],
                    as: 'paymentplans'
                }
            }
        ])

我希望我的结果应该是这样的

[
    {
        "key": "AA1",
        "label": "ALPHA",
        "paymentplans": [
            {
                "planName": "TV1",
                "planFeatures": {
                    "AA1": true,
                    "AA2": true,
                    "AA3": false
                },
                "__v": 0,
                "planFeatures5": [
                    {
                        "k": "AA1",
                        "v": true
                    }
                ]
            }
        ]
    }, ..............
]

这个问题我纠结了很久。 有人可以帮我吗?

$planFeatures5.k return 字符串数组,您应该在 $lookup 管道中的 $match 阶段使用 $in 运算符。

{
  $in: [
    "$$kkey",
    "$planFeatures5.k"
  ]
}
db.planFeatures.aggregate([
  {
    $lookup: {
      from: "plans",
      let: {
        "kkey": "$key"
      },
      pipeline: [
        {
          $set: {
            "planFeatures5": {
              "$objectToArray": "$planFeatures"
            }
          }
        },
        {
          $match: {
            $expr: {
              $in: [
                "$$kkey",
                "$planFeatures5.k"
              ]
            }
          }
        }
      ],
      as: "paymentplans"
    }
  }
])

Sample Mongo Playground