首页 > 解决方案 > MongoDB 聚合 - 嵌入式数组的投影中的 $filter

问题描述

我有一个复杂的 JSON 对象结构,其中包含 (N) 个嵌入式数组。单个条目是具有两个字段的对象: @namecontent。我需要在投影阶段过滤它们(不使用$unwind)以获得一个特定对象,其中@name字段等于特定值:

一种

 productCategory: {$filter: {
 input: '$characteristics.attributeGroup.attribute',
 as: 'attribute',
 cond: {
        ...?
 }}

输入返回上述$characteristics.attributeGroup.attribute结构。我试图在其中使用类似的东西,$cond: { $eq: ['$$attribute.@name', 'averageRating'] } 但它不起作用。

你能帮我在这里找到解决方案吗?

提前致谢!

标签: arraysmongodbaggregation-frameworkprojection

解决方案


你可以试试,

  • $reduce迭代数组循环attributeGroup,并使用返回合并对象$mergeObjects
  • 检查条件如果属性的类型是object然后再次检查第二个条件如果@name匹配则返回值否则移动到其他条件
  • $reduce迭代数组循环attribute,检查条件如果名称匹配则返回值
let name = "Artikelhinweise";
db.collection.aggregate([
  { $match: { "attributeGroup.attribute.@name": name } }, // name pass here
  {
    $project: {
      attributeGroup: {
        $reduce: {
          input: "$attributeGroup",
          initialValue: {},
          in: {
            $mergeObjects: [
              "$$value",
              {
                $cond: [
                  { $eq: [{ $type: "$$this.attribute" }, "object"] },
                  {
                    $cond: [
                      { $eq: ["$$this.attribute.@name", name] }, // name pass here
                      {
                        "@name": "$$this.attribute.@name",
                        "content": "$$this.attribute.content"
                      },
                      "$$value"
                    ]
                  },
                  {
                    $reduce: {
                      input: "$$this.attribute",
                      initialValue: {},
                      in: {
                        $cond: [
                          { $eq: ["$$this.@name", name] }, // name pass here
                          {
                            "@name": "$$this.@name",
                            "content": "$$this.content"
                          },
                          "$$value"
                        ]
                      }
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }
])

操场


推荐阅读