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

MongoDB中按季度分组文档并计算季度平均值的实现方法

实现MongoDB文档按季度分组并计算季度平均值

针对你的需求,我们可以通过MongoDB的聚合管道来完成,下面是完整的解决方案,包含字符串数值转换、数据过滤、季度分组以及平均值计算的全部逻辑:

聚合管道代码

db.yourCollectionName.aggregate([
  // 过滤掉sub_housing_type为"overall"的文档
  {
    $match: {
      sub_housing_type: { $ne: "overall" }
    }
  },
  // 将字符串格式的月份和消费值转为数值,同时清理字段中的换行符
  {
    $addFields: {
      month_num: { $toInt: "$month" },
      avg_mthly_kwh: {
        $toDouble: { $trim: { input: "$avg_mthly_hh_tg_consp_kwh", chars: "\r" } }
      }
    }
  },
  // 根据月份计算对应季度(1-4)
  {
    $addFields: {
      quarter: {
        $ceil: { $divide: ["$month_num", 3] }
      }
    }
  },
  // 按年、住房子类型、季度分组,统计总消费和有效月份数
  {
    $group: {
      _id: {
        year: "$year",
        sub_housing_type: "$sub_housing_type",
        quarter: "$quarter"
      },
      total_kwh: { $sum: "$avg_mthly_kwh" },
      month_count: { $sum: 1 }
    }
  },
  // 格式化输出字段,计算季度平均值并转为字符串格式
  {
    $project: {
      _id: 0,
      year: "$_id.year",
      quarter: { $toString: "$_id.quarter" },
      sub_housing_type: "$_id.sub_housing_type",
      quarterly_avg: { $toString: { $divide: ["$total_kwh", "$month_count"] } }
    }
  }
])

各阶段细节说明

  • $match阶段:直接排除sub_housing_type为"overall"的文档,确保后续计算只处理有效数据。
  • $addFields阶段:
    • 将month字符串转为整数类型,方便后续季度计算;
    • 用$trim移除avg_mthly_hh_tg_consp_kwh中的\r换行符,再转为双精度数值,解决字符串无法参与数值运算的问题。
  • 季度计算阶段:通过$divide将月份除以3,再用$ceil取上限值,得到对应季度(1-3月为Q1,4-6月为Q2,以此类推)。
  • $group阶段:按year、sub_housing_type、quarter分组,统计分组内的总消费和有效月份数(如果存在季度缺失月份的情况,用实际月份数做除数比固定除以3更严谨)。
  • $project阶段:重新整理输出字段,将季度和平均值转为字符串格式以匹配示例要求,同时移除默认生成的_id字段。

示例输出

运行上述聚合后,会得到符合需求的结果,示例如下:

{
  "year" : "2005",
  "quarter" : "1",
  "sub_housing_type" : "Public Housing",
  "quarterly_avg" : "89.4"
}

内容的提问来源于stack exchange,提问作者Charan Lime stone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:01:12