Mongo聚合:将值划分为组(按分区)

时间:2019-04-22 16:29:32

标签: mongodb aggregation-framework

使用this approach,我可以按时间对一组事件文档进行分组。此解决方案返回相同的输入文档,但添加了分区号。

我该如何做同样的事情,而是返回分区?输出文档示例为:

{
  partition: 0,
  startDate: ISODate("1900-04-12T18:30:00.000Z"),
  endDate: ISODate("2019-04-12T18:30:00.000Z"),
  numEvents: 27
}

1 个答案:

答案 0 :(得分:1)

假设这是您汇总的当前输出:

{
    "_id" : null,
    "datesWithPartitions" : [
        {
            "date" : ISODate("2019-04-12T18:30:00Z"),
            "partition" : 0
        },
        {
            "date" : ISODate("2019-04-12T20:00:00Z"),
            "partition" : 1
        },
        {
            "date" : ISODate("2019-04-12T20:10:00Z"),
            "partition" : 1
        },
        {
            "date" : ISODate("2019-04-12T21:00:00Z"),
            "partition" : 2
        },
        {
            "date" : ISODate("2019-04-12T21:15:00Z"),
            "partition" : 2
        },
        {
            "date" : ISODate("2019-04-12T21:45:00Z"),
            "partition" : 3
        },
        {
            "date" : ISODate("2019-04-12T23:00:00Z"),
            "partition" : 4
        }
    ]
}

要获取所需格式的数据,您需要附加以下聚合步骤:

db.col.aggregate([
    {
        $unwind: "$datesWithPartitions"
    },
    {
        $group: {
            _id: "$datesWithPartitions.partition",
            numEvents: { $sum: 1 },
            startDate: { $min: "$datesWithPartitions.date" },
            endDate: { $max: "$datesWithPartitions.date" }
        }
    },
    {
        $project: {
            _id: 0,
            partition: "$_id",
            startDate: 1,
            endDate: 1,
            numEvents: 1
        }
    }
])

$unwind将为每个文档返回单个日期,然后可以将$group$min$max一起使用以获取分区边界,并使用$sum来计算分区元素