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

MongoDB使用$lookup后无法计算AVG平均值与SUM总和求助

MongoDB聚合查询中$group无法正确计算数组字段的总和与平均值问题

我尝试获取MongoDB中集合的总计平均值和总和,使用$lookup能正确返回数据,但执行$group分组后,计算总和(sum)与平均值(total_average)时,这两个字段始终返回null或0。请问如何正确访问ventaPorCliente.total字段?

原聚合查询

db.clients.aggregate(
    [
        { 
            $lookup: { // DATA OK
                from: 'sales',
                localField: '_id',
                foreignField: 'clientId',
                as: 'ventaPorCliente'
            }
        },
        { 
            $group: { // total_average and sum null
                _id: "$idClient",
                username: { $first: "$name" },
                total_average: { $avg: 'ventaPorCliente.total'},
                sum: { $sum: 'ventaPorCliente.total'},
                count: { $sum: 1 }
            }
        },
    ]
)

原响应结果

[
  {
    "_id": "1",
    "username": "Peishion",
    "total_average": null,
    "sum": 0,
    "count": 1
  },
  {
    "_id": "1010",
    "username": "BENJAMIN",
    "total_average": null,
    "sum": 0,
    "count": 1
  }
]

问题原因

$lookup返回的ventaPorCliente是一个数组,直接写ventaPorCliente.total既没有正确引用数组内的字段,也缺少MongoDB字段引用必需的$前缀,导致聚合函数无法解析目标数值,最终返回null或0。

修复方案

  1. 拆分数组:在$lookup之后添加$unwind阶段,将数组拆分为单个文档,让后续聚合能访问到每个sales文档的total字段。
  2. 修正字段引用:在$group中使用$ventaPorCliente.total(带$前缀)的正确语法引用字段。

修正后的聚合查询

db.clients.aggregate(
    [
        { 
            $lookup: {
                from: 'sales',
                localField: '_id',
                foreignField: 'clientId',
                as: 'ventaPorCliente'
            }
        },
        { 
            $unwind: {
                path: "$ventaPorCliente",
                preserveNullAndEmptyArrays: true // 保留无关联销售记录的客户
            }
        },
        { 
            $group: {
                _id: "$idClient",
                username: { $first: "$name" },
                total_average: { $avg: "$ventaPorCliente.total" },
                sum: { $sum: "$ventaPorCliente.total" },
                count: { $sum: 1 }
            }
        }
    ]
)

补充说明

  • preserveNullAndEmptyArrays: true参数确保没有销售记录的客户也能出现在结果中,此时他们的sum为0,total_average为null;如果不需要这类客户,可以去掉该参数,$unwind会自动过滤数组为空的文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:10:38