比较嵌套数组中的对象 - mongoDB

Comparing objects inside a nested array - mongoDB

在我的数据库中,每个包含项目的文档中都有一个嵌套的元素数组,格式如下:

elements:[
     {
      "elem_id": 12,
      items: [ {"i_id": 1, "type": x}, {"i_id": 2, "type": y}, {"i_id": 3, "type": x}]
     },
     {
      "elem_id": 13,
      items: [ {"i_id": 4, "type": x}, {"i_id": 5, "type": x}]
     }
]

我正在尝试 return 所有具有不同类型项目的元素,这意味着我只会返回:

     {
      "elem_id": 12,
      items: [ {"i_id": 1, "type": x}, {"i_id": 2, "type": y}, {"i_id": 3, "type": x}]
      }

因为有 x 类型和 y 类型的项目。

我想我需要迭代项目数组并将数组中每个项目的类型与之前项目的类型进行比较,但我不知道如何在聚合中执行此操作。

请注意 - 我使用的是 Redash,所以我不能在查询中包含任何 JS。

感谢您的协助!

试试这个:

db.elements.aggregate([
    { $unwind: "$elements" },
    {
        $addFields: {
            "count": { $size: "$elements.items" },
            "uniqueValues": {
                $reduce: {
                    input: "$elements.items",
                    initialValue: [{ $arrayElemAt: ["$elements.items.type", 0] }],
                    in: {
                        $setUnion: ["$$value", ["$$this.type"]]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: {
                $eq: ["$count", { $size: "$uniqueValues" }]
            }
        }
    }
]);

输出:

{
    "_id" : ObjectId("603f8f05bcece4372062bcea"),
    "elements" : {
        "elem_id" : 12,
        "items" : [
            {
                "i_id" : 1,
                "type" : 1
            },
            {
                "i_id" : 2,
                "type" : 2
            },
            {
                "i_id" : 3,
                "type" : 3
            }
        ]
    },
    "count" : 3,
    "uniqueValues" : [1, 2, 3]
}