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

MongoDB按4层维度实现aggregation嵌套分组聚合查询方案咨询

MongoDB 四层嵌套分组聚合实现方案

原有代码错误点

  • 条件计数语法错误:$eq返回布尔值无法直接求和,需要用$cond将布尔值转换为1/0再累加
  • 语法错误:totalEnvC65行末尾缺少逗号,分组自定义字段名和业务字段不匹配
  • 仅完成了最细粒度的指标计算,缺少上层嵌套分组和结构转换逻辑

完整聚合管道代码

[
  // 步骤1:按最细四层维度分组,计算所有要求指标
  {
    $group: {
      _id: {
        client: "$client",
        service: "$service",
        expediteur: "$expediteur",
        tarif: "$tarif"
      },
      qte: { $count: {} },
      prix: { $first: "$prixAff" },
      totalAff: { $sum: "$prixAff" },
      totalEnvC65: {
        $sum: { $cond: [{ $eq: ["$enveloppe", "C65"] }, 1, 0] }
      },
      totalEnvC4: {
        $sum: { $cond: [{ $eq: ["$enveloppe", "C4"] }, 1, 0] }
      }
    }
  },
  // 步骤2:封装tarif层结构,生成 { tarif名称: 指标对象 } 格式的数组
  {
    $group: {
      _id: {
        client: "$_id.client",
        service: "$_id.service",
        expediteur: "$_id.expediteur"
      },
      tarifList: {
        $push: {
          k: "$_id.tarif",
          v: {
            qte: "$qte",
            prix: "$prix",
            totalAff: "$totalAff",
            totalEnvC65: "$totalEnvC65",
            totalEnvC4: "$totalEnvC4"
          }
        }
      }
    }
  },
  {
    $addFields: {
      tarifList: {
        $map: {
          input: "$tarifList",
          in: { $arrayToObject: [["$$this"]] }
        }
      }
    }
  },
  // 步骤3:封装expediteur层结构,生成 { expediteur名称: tarif数组 } 格式的数组
  {
    $group: {
      _id: {
        client: "$_id.client",
        service: "$_id.service"
      },
      expList: {
        $push: {
          k: "$_id.expediteur",
          v: "$tarifList"
        }
      }
    }
  },
  {
    $addFields: {
      expList: {
        $map: {
          input: "$expList",
          in: { $arrayToObject: [["$$this"]] }
        }
      }
    }
  },
  // 步骤4:封装service层结构,生成 { service名称: expediteur数组 } 格式的数组
  {
    $group: {
      _id: "$_id.client",
      serviceList: {
        $push: {
          k: "$_id.service",
          v: "$expList"
        }
      }
    }
  },
  {
    $addFields: {
      serviceList: {
        $map: {
          input: "$serviceList",
          in: { $arrayToObject: [["$$this"]] }
        }
      }
    }
  },
  // 步骤5:封装最外层client结构,生成最终要求的输出格式
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [[{ k: "$_id", v: "$serviceList" }]]
      }
    }
  }
]

输出说明

执行后输出结构完全匹配需求,最内层tarif维度的所有指标计算准确,四层嵌套结构完全按照client > service > expediteur > tarif的优先级排列。

内容的提问来源于stack exchange,提问作者Lionel KAISER

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:15:09