$sum窗口函数不能在$group中使用,因窗口函数仅支持$setwindowfields阶段;累计百分比需先$sort再$setwindowfields计算runningtotal,结合$lookup获取totalcount后$divide并$round处理。

为什么 $sum 窗口函数不能直接在 $group 阶段用
因为 MongoDB 的窗口函数(如 $sum 带 partitionBy 或 sortBy)只能在 $setWindowFields 阶段使用,而 $group 是聚合管道中更早、不支持窗口语义的阶段。试图在 $group 里写 { $sum: { $sum: "$count" } } 不仅语法错误,还会混淆“分组求和”和“累计求和”两个概念。
真正要算累计百分比,必须分两步:先得到每组的原始计数,再在有序序列上叠加窗口计算——否则无法定义“累计”从哪开始、按什么顺序加。
如何用 $setWindowFields 计算累计和并转为百分比
核心是把数据先按业务顺序排序(比如按日期、金额、排名),再用窗口函数逐行累加,最后除以全局总数。注意:窗口的 bounds 必须设为 { documents: ["unbounded", "current"] },否则不是“从头到当前”的累计。
-
$setWindowFields必须放在$sort之后,且字段名不能和上游重名(建议用runningTotal、totalCount这类明确语义的名) - 全局总数需提前用
$group算出并广播到每条文档,常用技巧是{ _id: null, totalCount: { $sum: "$count" } }+$lookup或$facet - 除法要防除零,建议用
{ $cond: { if: { $eq: ["$totalCount", 0] }, then: 0, else: { $divide: ["$runningTotal", "$totalCount"] } } }
[
{ $sort: { date: 1 } },
{ $set: { count: { $sum: 1 } } },
{
$setWindowFields: {
sortBy: { date: 1 },
output: {
runningTotal: { $sum: "$count", window: { documents: ["unbounded", "current"] } }
}
}
},
{
$lookup: {
from: "sales",
pipeline: [
{ $group: { _id: null, totalCount: { $sum: 1 } } }
],
as: "total"
}
},
{ $unwind: "$total" },
{
$set: {
cumulativePercent: {
$round: [
{ $multiply: [
{ $divide: ["$runningTotal", "$total.totalCount"] },
100
]
},
2
]
}
}
}
]
$setWindowFields 在分片集合上的限制与替代方案
如果集合已分片,$setWindowFields 会报错 "Window functions are not supported on sharded collections"。这不是配置问题,是 MongoDB 架构限制——窗口函数需要全量有序数据,分片后无法跨片保证全局顺序。
- 临时方案:用应用层读取全部数据后排序+累加(仅适用于结果集小、QPS 低的场景)
- 长期方案:改用物化视图(
$merge到非分片集合)或预计算字段(在写入时维护cumulativeCount) - 若只需“分组内累计”而非全局累计,可用
partitionBy: "$category"绕过部分限制,但百分比基数仍是该分组内总数,不是全集
为什么用 $round 而不是 JavaScript 的 toFixed
聚合管道中所有表达式都在服务端执行,没有 JavaScript 运行时。toFixed 是客户端方法,放进 $addFields 会直接报错 "invalid expression"。必须用 $round,且注意它只接受数字数组:{ $round: ["$value", 2] },不能写成 { $round: [{ $multiply: [...], 2 }] }(少一层括号就解析失败)。
另外,$round 对负数和 NaN 的行为和 JS 不同,如果上游可能产出非数字(比如 null 字段参与 $divide),务必用 $ifNull 或 $cond 清洗。











