Mongo aggregation within intervals of time

前端 未结 3 949
孤独总比滥情好
孤独总比滥情好 2021-02-04 20:57

I have some log data stored in a mongo collection that includes basic information as a request_id and the time it was added to the collection, for example:

{
            


        
3条回答
  •  [愿得一人]
    2021-02-04 21:39

    Something like this?

    pipeline = [
        {"$project":
            {"date": {
                "year": {"$year": "$time"},
                "month": {"$month": "$time"},
                "day": {"$dayOfMonth": "$time"},
                "hour": {"$hour": "$time"},
                "minute": {"$subtract": [
                    {"$minute": "$time"},
                    {"$mod": [{"$minute": "$time"}, 10]}
                ]}
            }}
        },
        {"$group": {"_id": "$date", "count": {"$sum": 1}}}
    ]
    

    Example:

    > db.foo.insert({"time": new Date(2015,  7, 21, 22, 21)})
    > db.foo.insert({"time": new Date(2015,  7, 21, 22, 23)})
    > db.foo.insert({"time": new Date(2015,  7, 21, 22, 45)})
    > db.foo.insert({"time": new Date(2015,  7, 21, 22, 33)})
    > db.foo.aggregate(pipeline)
    

    and output:

    { "_id" : { "year" : 2015, "month" : 8, "day" : 21, "hour" : 20, "minute" : 40 }, "count" : 1 }
    { "_id" : { "year" : 2015, "month" : 8, "day" : 21, "hour" : 20, "minute" : 20 }, "count" : 2 }
    { "_id" : { "year" : 2015, "month" : 8, "day" : 21, "hour" : 20, "minute" : 30 }, "count" : 1 }
    

提交回复
热议问题