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

MongoDB聚合按双字段分组时生成可排序唯一字段的方法

解决方案

完整聚合管道代码

let ap = [
  {
    $group: {
      _id: {
        year: { $year: '$itemDate' },
        month: { $month: '$itemDate' },
      },
      count: { $sum: 1 },
    },
  },
  // 添加格式化的key字段
  {
    $addFields: {
      key: {
        $concat: [
          { $toString: '$_id.year' },
          '-',
          { $lpad: [{ $toString: '$_id.month' }, 2, '0'] }
        ]
      }
    }
  },
  // 按年月升序排序
  {
    $sort: {
      '_id.year': 1,
      '_id.month': 1
    }
  }
];

关键说明

  1. 生成格式化key字段
    你之前用JS模板字符串的方式无效,因为MongoDB聚合管道不支持直接解析JS模板语法,必须使用MongoDB内置的聚合运算符:

    • $toString:将数字类型的年份、月份转换为字符串
    • $lpad:将月份字符串补零至2位(比如把1转为"01")
    • $concat:拼接年份、分隔符"-"、补零后的月份,生成YYYY-MM格式的key
  2. 按年月排序
    添加$sort阶段,直接根据_id.year和_id.month字段升序排列,即可得到按时间顺序整理的结果。

最终输出结果

[
  { _id: { year: 2022, month: 1 }, count: 76, key: '2022-01'},
  { _id: { year: 2022, month: 3 }, count: 259, key: '2022-03'},
  { _id: { year: 2022, month: 4 }, count: 232, key: '2022-04'},
  { _id: { year: 2022, month: 8 }, count: 12, key: '2022-08'},
  { _id: { year: 2022, month: 9 }, count: 2, key: '2022-09'},
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:16:04