Morgodb aggregation cast to int

I have the following problem with mongo using aggregation structure. Suppose also an element with time in seconds, t and an event taking place, e, for example: item: {t: 11433, e: some_id}

I want to aggregate by t and e. This means counting id 'e' over time t. This is easy to do using aggregation using $ group.

However, I would like to have a different course of time. For example, I want to count the number of identical event identifiers in a time interval, for example. 5 seconds. I could do it programmatically, in js or python. I'm just wondering if it can work using only mangoes, using a group cascade.

I tried to execute a project using $ divide [t, 10]. For 11433 this will give, 1143.3. But it seems that I cannot remove 0.3 in Mongo (otherwise I could group on this other scale).

Any clues?

thank

+5
source share
1 answer

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

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

In the aggregation structure, it will 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 } } },
])

In this example, the 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" }

result:

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

All Articles