【问题标题】:Comparing objects inside a nested array - mongoDB比较嵌套数组中的对象 - mongoDB
【发布时间】:2021-06-02 01:43:44
【问题描述】:

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

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 类型的项目。

我认为我需要迭代 items 数组并将数组中每个项目的类型与之前项目的类型进行比较,但我无法弄清楚如何在聚合中执行此操作。

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

感谢您的帮助!

【问题讨论】:

  • items 数组中的最后一个 item "elem_id": 12 必须是 "type": z 对吧?
  • 实际上它是 type: x 因为我只想检查至少有 2 个唯一键,而不是所有键都是唯一的。但是您的回答非常有帮助-我只需要在 [{$size: "uniqueValues"}, 2] 上使用 $gt 即可获得我想要的东西。谢谢!

标签: mongodb mongodb-query aggregation-framework redash


【解决方案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]
}

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多