MongoDB聚合转换为整数类型

5
我在使用Mongo的聚合框架时遇到了以下问题。 例如有一项具有以秒为单位的时间t和事件ID e 的项目,如下所示: item:{t:11433, e:some_id}
我想按照t和e进行聚合。这意味着统计在时间t内出现id“e”的数量。使用$group可以轻松完成此操作。
但是,我想要不同的时间间隔。例如,我希望在5秒的时间段内计算相同事件ID的数量。我可以在js或python中编程实现此操作。我只是想知道是否可以仅使用Mongo,使用级联组来完成此操作。
我尝试使用$divide [t,10]进行投影。对于11433,这将给出1143.3。但是在Mongo中似乎无法删除0.3(否则我可以在这个新的比例下进行分组)。
是否有任何提示?
谢谢

据我所知,这并不是聚合的一部分。 - Nuk Nuk San
1个回答

9
为了获得一个5秒的整数分组密钥,您可以使用以下公式。
t = t - (t % 5)  // % is the modula operator

在聚合框架中,这将如下所示:
db.xx.aggregate([
     // you need two projections, as they can not be nested
     // this does not work:
     // { $project: { _id: 0, e: 1, t: 1, tk: { $subtract: [ "$t", $mod: [ "$t", 5 ] ] } } },
     //
     // get modula 5 of time in seconds:
     { $project: { _id: 0, e: 1, t: 1, tm5: { $mod: [ "$t", 5 ] } } }, 
     // subtract it from time:
     { $project: { _id: 0, e: 1, ti: { $subtract: [ "$t", "$tm5" ] } } }, 
     // now group on e and interval, 
     { $group: { _id: { e: "$e", interval: "$ti" }, count: { $sum: 1 } } },
])

对于这个示例集合:

> db.xx.find()
{ "_id" : ObjectId("515e5a7157a0887a97cc8d1d"), "t" : 11433, "e" : "some_id" }
{ "_id" : ObjectId("515e60d457a0887a97cc8d1e"), "t" : 11434, "e" : "some_id" }
{ "_id" : ObjectId("515e60d857a0887a97cc8d1f"), "t" : 11438, "e" : "some_id" }

结果如下:

{
    "result" : [
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11435
            },
            "count" : 1
        },
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11430
            },
            "count" : 2
        }
    ],
    "ok" : 1
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接