Group result by 15 minutes time interval in MongoDb

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

    Another useful way:

    db.collection.aggregate([
      {$group: {
        _id: { 
          overallTime: { 
            $dateToString: { format: "%Y-%m-%dT%H", date: "$created_at" } 
          },
          interval: { $trunc: { $divide: [{ $minute: "$created_at" }, 15 ]}}
        },
      }},
    ])
    

    And more easier for min, hour, day intervals:

    var format = "%Y-%m-%dT%H:%M"; // 1 min
    var format = "%Y-%m-%dT%H"; // 1 hour
    var format = "%Y-%m-%d"; // 1 day
    
    db.collection.aggregate([
      {$group: {
        _id: { $dateToString: { format: format, date: "$created_at" } },
      }},
    ])
    

提交回复
热议问题