mongodb聚合转换为int

col*_*lin 5 mongodb aggregation-framework

我使用聚合框架的mongo有以下问题.假设和项目的时间以秒为单位,t和发生的事件ID,例如:item:{t:11433,e:some_id}

我想要的是根据t和e聚合.这意味着计算时间t中id'e'的数量.使用$ group聚合很容易做到这一点.

但是,我想有一个不同的时间课程.例如,我想在例如的时隙中计算相同事​​件id的数量.5秒.我可以在js或python中以编程方式执行此操作.我只是想知道它是否可以使用mongo,使用级联组.

我尝试使用$ divide [t,10]进行投影.对于11433,这将给出,1143.3但似乎我不能删除Mongo中的0.3(否则我可以在其他比例中分组).

任何提示?

谢谢

小智 9

要获取5秒间隔的整数组键,可以使用该公式

t = t - (t % 5)  // % is the modula operator
Run Code Online (Sandbox Code Playgroud)

在聚合框架中,这将如下所示:

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 } } },
])
Run Code Online (Sandbox Code Playgroud)

对于此示例集合:

> 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" }
Run Code Online (Sandbox Code Playgroud)

结果是:

{
    "result" : [
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11435
            },
            "count" : 1
        },
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11430
            },
            "count" : 2
        }
    ],
    "ok" : 1
}
Run Code Online (Sandbox Code Playgroud)