首页/数据/NoSQL 速查/聚合 $unwind 展开数组
本包目录(322 条)
MongoDB99 条
Elasticsearch89 条ClickHouse56 条时序与列式28 条选型与架构50 条

聚合 $unwind 展开数组

$unwind 把数组字段拆成多条输出文档(每条对应一个元素),是数组聚合与 $group 组合的常见前置步骤。

NoSQL 速查数据更新于 2026-10-12
语法{ $unwind: "$items" }
保留空数组preserveNullAndEmptyArrays: true
下标includeArrayIndex: "idx"
对象写法{ path: "$items", includeArrayIndex: "idx", preserveNullAndEmptyArrays: true }

展开订单明细

展开订单明细
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: "$items.sku", total: { $sum: "$items.qty" } } }
])
不带 preserveNullAndEmptyArrays 时,数组为空或缺失的文档会整条消失。

易错点

  • 大小写:路径必须写成 $items 形式,漏 $ 会直接报错

数据来源与参考

  • MongoDB Manual: $unwind
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌