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

MongoDB聚合查询时缺失字段如何填充前序文档的对应值

解决方案

你可以使用MongoDB的$reduce操作符先对log数组做预处理,遍历数组时维护上一个有效的connection_quality值,给缺失该字段的元素自动填充上一次的有效值,再展开输出即可。

注意你原有代码里的小问题:project阶段你引用的字段是$log.cq,但实际存储的字段名为connection_quality,需要先修正这个字段映射错误。

完整聚合管道如下:

[
  // 匹配指定的会议和用户
  {
    $match: {
      conf: 'conference123',
      uid: '2dd8b4e3-9dcd-4da6-bc36-aa0988dc9642'
    }
  },
  // 填充log数组中缺失的connection_quality字段
  {
    $addFields: {
      filled_log: {
        $reduce: {
          input: "$log",
          initialValue: {
            last_cq: null,
            logs: []
          },
          in: {
            last_cq: {
              $ifNull: ["$$this.connection_quality", "$$value.last_cq"]
            },
            logs: {
              $concatArrays: [
                "$$value.logs",
                [
                  {
                    $mergeObjects: [
                      "$$this",
                      {
                        connection_quality: {
                          $ifNull: ["$$this.connection_quality", "$$value.last_cq"]
                        }
                      }
                    ]
                  }
                ]
              ]
            }
          }
        }
      }
    }
  },
  // 提取处理完成的log数组
  {
    $addFields: {
      log: "$filled_log.logs"
    }
  },
  // 展开log数组
  {
    $unwind: "$log"
  },
  // 格式化输出字段
  {
    $project: {
      _id: 0,
      "Date": "$log.dt",
      "User ID": "$uid",
      "Connection Quality": "$log.connection_quality"
    }
  }
]

执行上述管道即可得到你期望的输出,所有缺失的Connection Quality都会自动继承上一条记录的有效值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 17:36:03