Javascript 聚合具有自定义时间段的mongodb记录
我有一个包含客户端报告的某些事件的集合,例如:Javascript 聚合具有自定义时间段的mongodb记录,javascript,mongodb,mongodb-query,aggregation-framework,Javascript,Mongodb,Mongodb Query,Aggregation Framework,我有一个包含客户端报告的某些事件的集合,例如: { "_id" : ObjectId("54f43159c922ac0b4387ef9c"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A
{ "_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.
但是我不知道如何定义$group
的\u id
:-(
我想要实现的输出如下:
{ "_id" : 0, "time":1425207775, "count" : 100 }
{ "_id" : 0, "time":1425210775, "count" : 51 }
{ "_id" : 0, "time":1425213775, "count" : 51 }
如果平台信息也能被识别出来就更好了。但是如果太复杂了,你可以提供一些参考,我会自己深入研究
如果您有任何建议,我们将不胜感激。这不是一个真正的问题,也不是太难。您只需要使用“日期数学”来处理您描述的“5分钟间隔”,因为这是一个“数字”而不是“日期”值。使用“日期”对象仍然可以(您应该真正使用它,因为在处理过程中几乎没有开销,也没有太大差异),但让我们坚持这一点:
db.event.aggregate([
{ "$match": { "clktime":{ "$gt": 1425204775 } } },
{ "$group": {
"_id": {
"$subtract": [
"$clktime",
"$mod": [ "$clktime", 60 * 5 ] // 5 minutes in seconds
]
},
"count": { "$sum": 1 }
}}
])
将值四舍五入到5分钟的间隔,即可在\u id
分组键中获取所需的分组数据
另外,\u id
值是“分组键”,因此您的预期结果无效,只能是“唯一分组”的结果。如果您熟悉SQL“分组依据”,这与SQL“分组依据”没有什么区别。这可能有用。