Group result by 15 minutes time interval in MongoDb

后端 未结 5 2103
野趣味
野趣味 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:15

    @Neil Lunn's answer at https://stackoverflow.com/a/26814496/8474325 for MongoDb 4.x upwards is fantastic. But there is a small mistake in the code where he uses ObjectId for the aggregation. The Line { "$toDate": "_id" } has to be changed to { "$toDate": "$_id" } for the code to work.

    Here's the corrected code.

    db.collection.aggregate([
        { "$group": {
          "_id": {
              "$toDate": {
                  "$subtract": [
                      { "$toLong": { "$toDate": "$_id" }  },
                      { "$mod": [ { "$toLong": { "$toDate": "$_id" } }, 1000 * 60 * 15 ] }
                  ]
              }
          },
          "count": { "$sum": 1 }
       }}
    ])
    

提交回复
热议问题