Group result by 15 minutes time interval in MongoDb

后端 未结 5 2038
野趣味
野趣味 2020-11-21 23:49

I have a \"status\" collection like this strcture -

{
    _id: ObjectId(\"545a0b63b03dbcd1238b4567\"),
    status: 1004,
    comment: \"Rem dolor ipsam place         


        
5条回答
  •  一生所求
    2020-11-22 00:06

    I like the other answer here, and mostly for the use of date math instead of aggregation date operators which while helpful can also be a little obscure.

    The only thing I want to add here is that you can also return a Date object from the aggregation framework by this approach as opposed to the "numeric" timestamp as the result. It's just a little extra math on the same principles, using $add:

    db.collection.aggregate([
        { "$group": {
            "_id": {
                "$add": [
                    { "$subtract": [
                        { "$subtract": [ "$current_date", new Date(0) ] },
                        { "$mod": [ 
                            { "$subtract": [ "$current_date", new Date(0) ] },
                            1000 * 60 * 15
                        ]}
                    ] },
                    new Date(0)
                ]
            },
            "count": { "$sum": 1 }
        }}
    ])
    

    The Date(0) contructs in JavaScript here represent the same "epoch" date in a shorter form, as 0 millisecond from epoch is epoch. But the main point is that when the "addition" to another BSON date object is done with a numeric identifier, then the inverse of the described condition is true and the end result is actually now a Date.

    All drivers will return the native Date type to their language by this approach.

提交回复
热议问题