You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB按小时间隔分组统计文档并生成所属时间区间

解决方案

你可以直接在MongoDB的聚合分组阶段中,利用分组_id里的时间字段构造出time_interval字段,无需在Python中额外处理。以下是修改后的分组代码:

{
  "_id": {
    "sensorId": "$sensorId",
    "year": { "$year": { "$toDate": { "$multiply": ["$captureTime", 1000] } } },
    "month": { "$month": { "$toDate": { "$multiply": ["$captureTime", 1000] } } },
    "day": { "$dayOfMonth": { "$toDate": { "$multiply": ["$captureTime", 1000] } } },
    "hour": { "$hour": { "$toDate": { "$multiply": ["$captureTime", 1000] } } }
    // 移除多余的interval字段,按hour分组已足够实现1小时间隔统计
  },
  "count": { "$sum": 1 },
  "time_f": { "$first": { "$dateToString": {
    "format": "%Y:%m:%d %H:%M:%S", 
    "date": { "$toDate": { "$multiply": ["$captureTime", 1000] } } }}},
  "time_l": { "$last": { "$dateToString": {
    "format": "%Y:%m:%d %H:%M:%S", 
    "date": { "$toDate": { "$multiply": ["$captureTime", 1000] } } }}},
  "device_Id_f": {"$first": "$deviceId"},
  "sensor_Id_f": {"$first": "$sensorId"},
  "time_interval": {
    "$dateToString": {
      "format": "%Y:%m:%d %H:%M:%S",
      "date": {
        "$add": [
          // 用分组参数构造当前小时的起始时间
          {
            "$dateFromParts": {
              "year": "$_id.year",
              "month": "$_id.month",
              "day": "$_id.day",
              "hour": "$_id.hour"
            }
          },
          3600000 // 加1小时毫秒数,得到区间结束时间
        ]
      }
    }
  }
}

代码说明

  1. 移除冗余字段:原代码中interval的计算结果始终为0(分钟数对60取余后与自身相减),对小时分组无实际作用,删除后简化逻辑。
  2. 生成time_interval:
    • 通过$dateFromParts结合分组的年、月、日、小时参数,生成当前小时的起始时间。
    • 加上3600000毫秒(1小时)得到区间结束时间,再用$dateToString格式化为你需要的字符串格式,与示例输出匹配。

若需要将time_interval设为区间起始时间(如2024:01:01 00:00:00),只需去掉$add步骤,直接格式化$dateFromParts的结果即可。

内容的提问来源于stack exchange,提问作者Rirro Romeu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:44:52