我有一个集合,其中包含客户端报告的一些事件,例如:
{ "_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分钟报告了多少个事件( by 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
的 _id
:-(
我想要实现的输出是这样的:
{ "_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/