Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb aggregation cast to int

I have the following problem with mongo using the aggregation framework. Suppose and item with time in seconds, t, and an event id occurring, e, like: item:{t:11433, e:some_id}

what I want is to aggregate according to t and e. It means counting the number of id 'e' in a time t. This is easy to do using the aggregation with $group.

However, I would like to have a different time course. For example, I want to count number of same event id in a time slot of eg. 5 seconds. I could do this progammatically, in js or python . I was just wondering if it could work using just mongo, using a cascade of group.

I tried to project using $divide[t,10]. For 11433, this would give, 1143.3 But it seems that I can't remove the 0.3 in Mongo (Otherwise I could group in this other scale).

Any hint?

thanks

like image 933
colin Avatar asked Mar 15 '13 16:03

colin


1 Answers

To get an integer group key for a 5-second interval, you could use the formula

t = t - (t % 5)  // % is the modula operator

In the aggregation framework this would look like this:

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 } } },
])

For this example collection:

> 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" }

the result is:

{
    "result" : [
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11435
            },
            "count" : 1
        },
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11430
            },
            "count" : 2
        }
    ],
    "ok" : 1
}
like image 100
ronasta Avatar answered Nov 15 '22 09:11

ronasta