在 MongoDB 中按时聚合查询

Aggregate query on time in MongoDB

我正在使用 MongoDB 聚合管道,对于我想做的大部分事情,它到目前为止都很完美。

但是,我想按天、小时或分钟汇总时间和分组。这是我到目前为止的查询(在分钟粒度的情况下:

db.track.aggregate(
  [
    {$match: {event: /pricing/i}},
    {$unwind:"$userId"},
    {
      $group: {
        _id: {min: {$minute: "$timestamp"}},
        count: {$sum: 1}
      }
    }
  ]
)

这里明显的问题是它将不同时间的分钟组合在一起。像这样:

{ "_id" : { "min" : 18 }, "count" : 8 }
{ "_id" : { "min" : 33 }, "count" : 18 }
{ "_id" : { "min" : 10 }, "count" : 6 }
{ "_id" : { "min" : 8 }, "count" : 2 }
{ "_id" : { "min" : 43 }, "count" : 2 }
{ "_id" : { "min" : 35 }, "count" : 6 }
{ "_id" : { "min" : 46 }, "count" : 2 }
{ "_id" : { "min" : 12 }, "count" : 4 }
{ "_id" : { "min" : 31 }, "count" : 4 }
{ "_id" : { "min" : 4 }, "count" : 14 }

我想在图表中使用该查询的结果。理想情况下,我想找回类似的东西:

{ "_id" : { "time" : "14:04" }, "count" : 14 }

我的文档是这样的

{
    _id: ObjectId("54cd7b8f7e4515a41898faac"),
    userId: [
        "xp1ungmsrh3hbhjk7c2go45xxvh0uiaa9rel5",
        "a3c10b3c-3825-4b32-9a57-0e75b508d5bb"
    ],
    type: "track",
    timestamp: ISODate("2015-02-01T01:04:13.632Z"),
    event: "View Pricing Page"
}

我确定我在这里遗漏了一些明显的东西,但是 the doc 没有给我任何其他继续下去的东西。

谁能给我指出正确的方向?

您需要结合使用 $group 中的组合 _id 和 $project 来创建时间。

db.track.aggregate(
  [
    {$match: {event: /pricing/i}},
    {$unwind:"$userId"},
    {
      $group: {
        _id: {min: {$minute: "$timestamp"}, hour: {$hour: "$timestamp"}},
        count: {$sum: 1}
      }
    },
    {$project: {time: {$concat:["$hour",":","$min"]}}}
  ]
)

阿联酋这个查询:

db.track.aggregate(
  [
    { $match: {event: /pricing/i} },
    { $unwind: "$userId" },
    {
      $group: 
      {
        _id: 
        {
            hour : { $hour : "$timestamp" },
            min: { $minute : "$timestamp" }
        },
        count: {$sum : 1}
      }
    },
    { $project : { _id : 0, count: 1, time : { $concat :[ {$substr:['$_id.hour', 0, 4]}, ':', {$substr:['$_id.min', 0, 4]}] }} },
  ]
)

示例输出:

{
    "result" : [ 
        {
            "count" : 2,
            "time" : "1:4"
        }
    ],
    "ok" : 1
}

如果您将最后一个 $project 更改为以下,输出将与您提到的完全相同

{ $project : { _id : 0, count: 1, '_id.time' : { $concat :[ {$substr:['$_id.hour', 0, 4]}, ':', {$substr:['$_id.min', 0, 4]}] }} },

输出:

{
    "result" : [ 
        {
            "_id" : {
                "time" : "1:4"
            },
            "count" : 2
        }
    ],
    "ok" : 1
}