【问题标题】:Aggregate mongodb records with self-defined time period聚合自定义时间段的mongodb记录
【发布时间】:2015-03-02 10:24:31
【问题描述】:

我有一个集合,其中包含客户端报告的一些事件,例如:

{ "_id" : ObjectId("54f43159c922ac0b4387ef9c"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B31" }
{ "_id" : ObjectId("54f43159c922ac0b4387ef9d"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B32" }
{ "_id" : ObjectId("54f43159c922ac0b4387ef9e"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "facebook", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B33" }
{ "_id" : ObjectId("54f43159c922ac0b4387ef9f"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B34" }

你可以看到clktime是一个unix时间戳(自定义,不是Mongodb生成的),精度为Second,我想知道每个paltform每5分钟报告了多少事件(clktime) ,我知道我应该使用mongodb的Aggregate框架如:

 db.event.aggregate([{$match:{clktime:{$gt:1425204775}}},{$group:{_id:???, count:{$sum:1}}}])
                                                                      ^^^
                                                                       I really don't know what this _id should be.

但我不知道如何定义$group_id :-(

我想要实现的输出是这样的:

{ "_id" : 0, "time":1425207775, "count" : 100 }
{ "_id" : 0, "time":1425210775, "count" : 51 }
{ "_id" : 0, "time":1425213775, "count" : 51 }

如果平台信息也能识别出来就更好了。但如果太复杂,你可以提供一些参考,我会自己深入研究。

任何建议将不胜感激。

【问题讨论】:

  • 这个link 可能有用。

标签: javascript mongodb mongodb-query aggregation-framework


【解决方案1】:

真的不是问题,也不是太难。您只需要“日期数学”来处理您描述的“5 分钟间隔”,因为这是一个“数字”而不是“日期”值。仍然可以使用“日期”对象(您应该真正使用它,因为几乎没有开销,并且在处理方面没有太大差异),但让我们坚持这一点:

db.event.aggregate([
    { "$match": { "clktime":{ "$gt": 1425204775 } } },
    { "$group": {
        "_id": {
            "$subtract": [
                "$clktime",
                "$mod": [ "$clktime",  60 * 5 ]   // 5 minutes in seconds
            ]
        },
        "count": { "$sum": 1 }
    }}
])

将值四舍五入到 5 分钟的间隔会在 _id 分组键中获得您想要的分组数据。

_id 值也是“分组键”,因此您的预期结果无效,它只能是“唯一分组”的内容。如果您熟悉的话,这与 SQL "GROUP BY" 并没有什么不同。

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2022-11-23
    • 2021-07-21
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多