比较MongoDB中嵌套数组内的对象

4

在我的数据库中,每个文档都包含一个元素的嵌套数组,其中包含以下形式的项:

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}]
     }
]

我试图返回所有具有不同类型项的元素,这意味着我只会得到以下内容:
     {
      "elem_id": 12,
      items: [ {"i_id": 1, "type": x}, {"i_id": 2, "type": y}, {"i_id": 3, "type": x}]
      }

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

我认为我需要迭代项目数组并比较数组中每一项的类型与之前项目的类型,但我无法弄清楚如何在聚合中实现这一点。

需要注意的是- 我正在使用Redash,因此无法在查询中包含任何JS。

谢谢您的帮助!


对于 "elem_id": 12items 数组的最后一个 item 必须是 "type": z,对吗? - Dheemanth Bhat
1
实际上它是类型:x,因为我只想检查是否至少有两个唯一的键,而不是所有都是唯一的。但是你的答案非常有帮助 - 我只需要在 [{$size: "uniqueValues"}, 2] 上使用 $gt 就可以得到我想要的结果。谢谢! - Roni
2个回答

1

试试这个:

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]
}

0

你可以简化答案(不需要使用$reduce$addFields):

db.collection.aggregate([
  {$unwind: "$elements"},
  {$match: {
      $expr: {$gt:[
        {$size: {$setIntersection: ["$elements.items.type", "$elements.items.type"]}},  
        1
      ]}
  }}
])

示例游乐场上查看它的工作原理


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接