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

{ "_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生成的),精度为秒,我想知道每个Paltform每5分钟报告了多少个事件(通过clktime),我知道应该使用MongoDB的聚合框架,例如:
 db.event.aggregate([{$match:{clktime:{$gt:1425204775}}},{$group:{_id:???, count:{$sum:1}}}])
                                                                      ^^^
                                                                       I really don't know what this _id should be.

但我不知道如何定义-(
我想要实现的输出如下:
{ "_id" : 0, "time":1425207775, "count" : 100 }
{ "_id" : 0, "time":1425210775, "count" : 51 }
{ "_id" : 0, "time":1425213775, "count" : 51 }

如果平台信息也能被识别出来,那就更好了。但如果太复杂的话,你可以给我一些参考,我会亲自研究的。
任何建议都将不胜感激。

最佳答案

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

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”没有什么不同。

关于javascript - 聚合具有自定义时间段的mongodb记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28807426/

10-09 06:38
查看更多