$unwind是唯一能将含数组文档“炸开”为多文档的操作符,$reduce仅做字段内计算、不改变文档数量;多次$unwind须从外到内、逐层设置preservenullandemptyarrays:true,且需$project及时提取字段防污染。

$unwind 是唯一可靠、语义清晰的多层嵌套数组展开方式;$reduce 不能替代 $unwind,它不产生新文档,只做字段内计算。
为什么 $unwind 是必须的,而 $reduce 不行
你看到的“用 $reduce 展开数组”基本是误解。$reduce 作用于单个数组字段,返回一个标量或对象,$reduce 输出仍是原文档中一个字段的值,不会让一条原始文档变成多条——而这正是“展开”的本质要求。$unwind 才是聚合管道中唯一能将一个含数组的文档“炸开”成 N 条文档的操作符。
常见错误现象:$reduce 配合 $concatArrays 或 $map 后试图直接 $group 或 $lookup,结果发现关联失败、计数不准、字段丢失——因为文档数量没变,只是字段内容变了。
-
$unwind改变文档流数量(1 → N),是数据形态转换; -
$reduce改变字段值([a,b] → a+b),是字段内运算; - 想把
user.courses和user.courses.requirements.subjects全部摊平?必须用$unwind多次,不能靠$reduce“一步到位”。
多次 $unwind 的正确顺序与 preserveNullAndEmptyArrays
嵌套越深,$unwind 越容易丢文档。比如 user.courses 存在但 courses.requirements 为空数组,第二个 $unwind 默认会过滤掉该文档——这不是你想要的“保留用户但无需求”的语义。
必须显式开启 preserveNullAndEmptyArrays: true:
{ $unwind: { path: "$courses", preserveNullAndEmptyArrays: true } }
{ $unwind: { path: "$courses.requirements", preserveNullAndEmptyArrays: true } }
{ $unwind: { path: "$courses.requirements.subjects", preserveNullAndEmptyArrays: true } }
注意:每个 $unwind 都要单独写,不能合并;路径必须精确到当前层级可展开的字段(如不能对 $courses.requirements.subjects 一次 unwind 三层)。
- 空数组、
null、缺失字段,三者行为不同:preserveNullAndEmptyArrays: true只保空数组和null,不保缺失字段(需先$set默认值); - 顺序不能乱:必须从外到内,先
$unwind: "$courses",再$unwind: "$courses.requirements",否则路径无效; - 性能敏感场景下,建议在第一个
$match尽量缩小输入集,避免对大量空数组反复 unwind。
遇到“数组里套对象,对象里又套数组”怎么办
典型结构:{"items": [{"tags": ["a","b"], "meta": {"attrs": ["x","y"]}}]}。你想把 items.tags 和 items.meta.attrs 全部扁平化为同级字段?不能只靠两次 $unwind,因为它们属于同一层级的不同子字段。
你需要分叉处理再合并:
{ $unwind: { path: "$items", preserveNullAndEmptyArrays: true } }
{ $unwind: { path: "$items.tags", preserveNullAndEmptyArrays: true } }
{ $unwind: { path: "$items.meta.attrs", preserveNullAndEmptyArrays: true } }
{ $project: { tag: "$items.tags", attr: "$items.meta.attrs", _id: 1 } }
关键点:
- 所有
$unwind都基于当前文档结构,不是“全局展开”; - 如果两个数组长度不一致(如
tags长 2、attrs长 3),$unwind会做笛卡尔积,产生 6 条文档——这是预期行为,不是 bug; - 若要避免笛卡尔积,得先用
$map+$zip对齐,再$unwind,但逻辑复杂度陡增,通常应前置业务约束(如规定两数组等长)。
真正容易被忽略的坑:$unwind 后的字段引用和别名污染
多次 $unwind 后,原始字段名还在,但值已变成单元素。比如 $unwind: "$items" 后,$items 变成一个对象;再 $unwind: "$items.tags" 后,$items.tags 变成字符串,但 $items 本身仍存在且完整——这会导致后续 $group 或 $project 时误用未展开的父字段。
最稳妥做法:每轮 $unwind 后立即 $project 显式提取所需字段,丢弃冗余嵌套:
{ $project: { tag: "$items.tags", attr: "$items.meta.attrs", user_id: "$_id" } }
否则你会在调试时发现:$items.tags 在日志里显示正常,但 $group 按它分组却分不出结果——因为实际参与分组的是展开前的整个数组,而不是你眼睛看到的那个字符串。











