You need to enable JavaScript to run this app. MongoDB聚合中如何对比两个数组并补全缺失日期的用户统计数据
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合中如何对比两个数组并补全缺失日期的用户统计数据

MongoDB聚合实现补全日期统计值方案

实现思路

通过遍历指定日期范围数组dayRange,逐个匹配已有日统计数据,匹配不到的日期自动补0,最终生成完整的日统计数组。

兼容MongoDB 5.0+的聚合语句

db.collection.aggregate([
  {
    $addFields: {
      // 覆盖原有userCountPerDay字段,生成补全后的统计数组
      userCountPerDay: {
        $map: {
          input: "$dayRange", // 以日期范围数组为遍历基准,保证日期完整、顺序正确
          as: "currentDate",
          in: {
            $let: {
              vars: {
                // 匹配当前日期对应的统计记录
                matchedRecord: {
                  $first: {
                    $filter: {
                      input: "$userCountPerDay",
                      cond: { $eq: ["$$this.createdAt", "$$currentDate"] }
                    }
                  }
                }
              },
              in: {
                createdAt: "$$currentDate",
                // 匹配不到则userCount默认设为0
                userCount: { $ifNull: ["$$matchedRecord.userCount", 0] }
              }
            }
          }
        }
      }
    }
  },
  // 可选阶段:不需要保留原dayRange字段可开启
  // { $project: { dayRange: 0 } }
])

低版本MongoDB(<5.0)兼容写法

如果使用的MongoDB版本不支持$first操作符,将$first替换为$arrayElemAt取数组第一个元素即可:

// 仅列修改的matchedRecord部分,其余结构不变
matchedRecord: {
  $arrayElemAt: [
    {
      $filter: {
        input: "$userCountPerDay",
        cond: { $eq: ["$$this.createdAt", "$$currentDate"] }
      }
    },
    0
  ]
}

效果说明

  • 生成的userCountPerDay数组顺序和dayRange日期顺序完全一致
  • 所有dayRange中包含的日期都会出现在结果中,无统计数据的日期userCount自动为0
  • 原有dayCount、totalUserCount字段不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 11:06:06