Group result by 15 minutes time interval in MongoDb -
i have "status" collection strcture -
{ _id: objectid("545a0b63b03dbcd1238b4567"), status: 1004, comment: "rem dolor ipsam placeat omnis non. aspernatur nobis qui nisi similique.", created_at: isodate("2014-11-05t11:34:59.804z") }, { _id: objectid("545a0b66b03dbcd1238b4568"), status: 1001, comment: "sint et eos vero ipsa voluptatem harum. hic unde voluptatibus et blanditiis quod modi.", created_at: isodate("2014-11-05t11:35:02.814z") } .... ....
i need result grouped 15 minutes interval collection.
there couple of ways this.
the first date aggregation operators, allow dissect "date" values in documents. "grouping" primary intent:
db.collection.aggregate([ { "$group": { "_id": { "year": { "$year": "$created_at" }, "dayofyear": { "$dayofyear": "$created_at" }, "interval": { "$subtract": [ { "$minute": "$created_at" }, { "$mod": [{ "$minute": "$created_at"}, 15] } ] } }}, "count": { "$sum": 1 } }} ])
the second way using little trick of when date object subtracted (or other direct math operation) date object, result numeric value representing epoch timestamp milliseconds between 2 objects. using epoch date epoch milliseconds representation. use date math interval:
db.collection.aggregate([ { "$group": { "_id": { "$subtract": [ { "$subtract": [ "$current_date", new date("1970-01-01") ] }, { "$mod": [ { "$subtract": [ "$current_date", new date("1970-01-01") ] }, 1000 * 60 * 15 ]} ] }, "count": { "$sum": 1 } }} ])
so depends on kind of output format want grouping interval. both represent same thing , have sufficient data re-construct "date" object in code.
you can put else want in "grouping operator" portion after grouping _id
. i'm using basic "count" example in lieu of real statement want do.
Comments
Post a Comment