对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$unwind(聚合阶段)

$unwind

解构输入文档中的数组字段,以便为每个元素输出文档。每个输出文档都是输入文档,并用该元素替换该数组字段的值。

可以使用 $unwind 查找托管在以下环境中的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

您可传递字段路径操作数或文档操作数来展开数组字段。

您可以将数组字段路径传递给 $unwind。使用该语法时,如果字段值为 null、缺失或空数组,则 $unwind 不会输出文档。

{ $unwind: <field path> }

如需指定字段路径,在字段名称前加上美元符号 $,并用引号括起来。

您可以将文档传递给 $unwind 以指定各种行为选项。

{ $unwind: { path: <field path>, includeArrayIndex: <string>, preserveNullAndEmptyArrays: <boolean> }}
字段
类型
说明

字符串

数组字段的字段路径。如需指定字段路径,请在字段名称前加上美元符号 $,并用引号括起来。

字符串

可选。新字段的名称,用于保存该元素的数组索引。名称不能以美元符号 $ 开头。

布尔

可选。

  • 如果为 true,如果 path 缺失或是空数组,$unwind 将在输出文档中忽略输出字段。如果值为 null,则该字段仍为 null。

  • 如果为 false,如果 path 为 null、缺失或空大量,则 $unwind 不会输出文档。

默认值为 false。

当 path 的值未解析为数组时,$unwind 的行为如下:

  • 如果该值未缺失、不是 null 且不是空数组,则 $unwind 会按原样使用该值输出单个文档。

  • 如果指定了 includeArrayIndex,则数组输入的索引为 0,非数组输入的索引为 null。列表中靠后的文档的索引大于 0。

  • 如果该值缺失、为 null 或空数组,则 $unwind 遵循 keepNullAndEmptyArrays 选项。当指定 includeArrayIndex 并保留文档时,索引为 null。

如果为输入文档中不存在的字段指定路径,或者字段为空数组,$unwind 默认会忽略此输入文档,不会输出该输入文档的文档。

请使用 preserveNullAndEmptyArrays 选项输出数组字段缺失、为 null 或空数组的文档。

在 mongosh 中创建名为 inventory 的示例集合,其中包含以下文档:

db.inventory.insertOne({ _id: 1, item: "ABC1", sizes: [ "S", "M", "L"] })

以下聚合使用 $unwind 阶段为 sizes 数组中的每个元素输出一个文档:

db.inventory.aggregate( [ { $unwind : "$sizes" } ] )

操作返回以下结果:

{ _id: 1, item: "ABC1", sizes: "S" }{ _id: 1, item: "ABC1", sizes: "M" }{ _id: 1, item: "ABC1", sizes: "L" }

每个文档都与输入文档完全相同,只是 sizes 字段的值不同,该字段现在采用原始 sizes 数组的值。

考虑 clothing 集合。

db.clothing.insertMany([ { _id: 1, item: "Shirt", sizes: [ "S", "M", "L"] }, { _id: 2, item: "Shorts", sizes: [ ] }, { _id: 3, item: "Hat", sizes: "M" }, { _id: 4, item: "Gloves" }, { _id: 5, item: "Scarf", sizes: null }])

如果满足以下条件,则 $unwind 将 sizes 字段视为单元素数组:

  • 该字段存在,

  • 该值不为空,并且

  • 该值不是空数组。

用 $unwind 展开 sizes 数组:

db.clothing.aggregate( [ { $unwind: { path: "$sizes" } } ] )

$unwind 操作返回:

{ _id: 1, item: 'Shirt', sizes: 'S' },{ _id: 1, item: 'Shirt', sizes: 'M' },{ _id: 1, item: 'Shirt', sizes: 'L' },{ _id: 3, item: 'Hat', sizes: 'M' }
  • 在文档 "_id": 1 中,sizes 是一个填充数组。$unwind 为 sizes 字段中的每个元素返回一个文档。

  • 在文档 "_id": 3 中,sizes 解析为单元素数组。

  • 文档 "_id": 2, "_id": 4 和 "_id": 5 不会返回任何内容,因为 sizes 字段无法还原为单元素数组。

注意

{ path: <FIELD> } 语法是可选的。以下 $unwind 操作是等效的。

db.clothing.aggregate( [ { $unwind: "$sizes" } ] )db.clothing.aggregate( [ { $unwind: { path: "$sizes" } } ] )

preserveNullAndEmptyArrays 和 includeArrayIndex 示例使用了以下集合:

db.inventory2.insertMany([ { _id: 1, item: "ABC", price: Decimal128("80"), sizes: [ "S", "M", "L"] }, { _id: 2, item: "EFG", price: Decimal128("120"), sizes: [ ] }, { _id: 3, item: "IJK", price: Decimal128("160"), sizes: "M" }, { _id: 4, item: "LMN" , price: Decimal128("10") }, { _id: 5, item: "XYZ", price: Decimal128("5.75"), sizes: null }])

以下 $unwind 操作使用 preserveNullAndEmptyArrays 选项来纳入 sizes 字段为 null、缺失或空数组的文档。

db.inventory2.aggregate( [ { $unwind: { path: "$sizes", preserveNullAndEmptyArrays: true } }] )

输出包括 sizes 字段为 null、缺失或空数组的文档:

{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "S" }{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "M" }{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "L" }{ _id: 2, item: "EFG", price: Decimal128("120") }{ _id: 3, item: "IJK", price: Decimal128("160"), sizes: "M" }{ _id: 4, item: "LMN", price: Decimal128("10") }{ _id: 5, item: "XYZ", price: Decimal128("5.75"), sizes: null }

以下 $unwind 操作使用 includeArrayIndex 选项以在输出中纳入数组索引。

db.inventory2.aggregate( [ { $unwind: { path: "$sizes", includeArrayIndex: "arrayIndex" } }])

该操作展开 sizes 数组并将该数组索引包含在新的 arrayIndex 字段中。如果 sizes 字段未解析为填充数组,但不缺失、不为 null 或空数组,则 arrayIndex 字段为 null。

{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "S", arrayIndex: Long(0) }{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "M", arrayIndex: Long(1) }{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "L", arrayIndex: Long(2) }{ _id: 3, item: "IJK", price: Decimal128("160"), sizes: "M", arrayIndex: null }

在 mongosh 中创建名为 inventory2 的示例集合,其中包含以下文档:

db.inventory2.insertMany([ { _id: 1, item: "ABC", price: Decimal128("80"), sizes: [ "S", "M", "L"] }, { _id: 2, item: "EFG", price: Decimal128("120"), sizes: [ ] }, { _id: 3, item: "IJK", price: Decimal128("160"), sizes: "M" }, { _id: 4, item: "LMN" , price: Decimal128("10") }, { _id: 5, item: "XYZ", price: Decimal128("5.75"), sizes: null }])

以下管道会展开 sizes 数组,并按展开的大小值对生成的文档进行分组:

db.inventory2.aggregate( [ // First Stage { $unwind: { path: "$sizes", preserveNullAndEmptyArrays: true } }, // Second Stage { $group: { _id: "$sizes", averagePrice: { $avg: "$price" } } }, // Third Stage { $sort: { "averagePrice": -1 } }] )
第一个阶段:

$unwind 阶段为 sizes 数组中的每个元素输出一个新文档。该阶段使用 preserveNullAndEmptyArrays 选项以在输出中包含 sizes 字段缺失、为 null 或空数组的文档。该阶段将以下文档传递到下一阶段:

{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "S" }{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "M" }{ _id: 1, item: "ABC", price: Decimal128("80"), sizes: "L" }{ _id: 2, item: "EFG", price: Decimal128("120") }{ _id: 3, item: "IJK", price: Decimal128("160"), sizes: "M" }{ _id: 4, item: "LMN", price: Decimal128("10") }{ _id: 5, item: "XYZ", price: Decimal128("5.75"), sizes: null }
第二个阶段:

$group 阶段按 sizes 对文档进行分组,并计算每种尺寸的平均价格。该阶段将以下文档传递到下一阶段:

{ _id: "S", averagePrice: Decimal128("80") }{ _id: "L", averagePrice: Decimal128("80") }{ _id: "M", averagePrice: Decimal128("120") }{ _id: null, averagePrice: Decimal128("45.25") }
第三个阶段:

$sort 阶段按 averagePrice 降序对文档进行排序。该操作返回以下结果:

{ _id : "M", averagePrice: Decimal128("120") }{ _id : "L", averagePrice: Decimal128("80") }{ _id : "S", averagePrice: Decimal128("80") }{ _id : null, averagePrice: Decimal128("45.25") }

提示

在 mongosh 中创建名为 sales 的示例集合,其中包含以下文档:

db.sales.insertMany( [ { _id: "1", items: [ { name: "pens", tags: [ "writing", "office", "school", "stationary" ], price: Decimal128("12.00"), quantity: Int32("5") }, { name: "envelopes", tags: [ "stationary", "office" ], price: Decimal128("19.95"), quantity: Int32("8") } ] }, { _id: "2", items: [ { name: "laptop", tags: [ "office", "electronics" ], price: Decimal128("800.00"), quantity: Int32("1") }, { name: "notepad", tags: [ "stationary", "school" ], price: Decimal128("14.95"), quantity: Int32("3") } ] }])

下面的操作按标签对已售出的物品进行分组,然后计算每个标签的总销售额。

db.sales.aggregate([ // First Stage { $unwind: "$items" }, // Second Stage { $unwind: "$items.tags" }, // Third Stage { $group: { _id: "$items.tags", totalSalesAmount: { $sum: { $multiply: [ "$items.price", "$items.quantity" ] } } } }])
第一个阶段:

第一个 $unwind 阶段为 items 数组中的每个元素输出一个新文档:

{ _id: "1", items: { name: "pens", tags: [ "writing", "office", "school", "stationary" ], price: Decimal128("12.00"), quantity: 5 } }{ _id: "1", items: { name: "envelopes", tags: [ "stationary", "office" ], price: Decimal128("19.95"), quantity: 8 } }{ _id: "2", items: { name: "laptop", tags: [ "office", "electronics" ], price: Decimal128("800.00"), quantity": 1 } }{ _id: "2", items: { name: "notepad", tags: [ "stationary", "school" ], price: Decimal128("14.95"), quantity: 3 } }
第二阶段

第二个 $unwind 阶段为 items.tags 数组中的每个元素输出一个新文档:

{ _id: "1", items: { name: "pens", tags: "writing", price: Decimal128("12.00"), quantity: 5 } }{ _id: "1", items: { name: "pens", tags: "office", price: Decimal128("12.00"), quantity: 5 } }{ _id: "1", items: { name: "pens", tags: "school", price: Decimal128("12.00"), quantity: 5 } }{ _id: "1", items: { name: "pens", tags: "stationary", price: Decimal128("12.00"), quantity: 5 } }{ _id: "1", items: { name: "envelopes", tags: "stationary", price: Decimal128("19.95"), quantity: 8 } }{ _id: "1", items: { name: "envelopes", tags: "office", "price" : Decimal128("19.95"), quantity: 8 } }{ _id: "2", items: { name: "laptop", tags: "office", price: Decimal128("800.00"), quantity: 1 } }{ _id: "2", items: { name: "laptop", tags: "electronics", price: Decimal128("800.00"), quantity: 1 } }{ _id: "2", items: { name: "notepad", tags: "stationary", price: Decimal128("14.95"), quantity: 3 } }{ _id: "2", items: { name: "notepad", "ags: "school", price: Decimal128("14.95"), quantity: 3 } }
第三个阶段

$group 阶段按标签对文档进行分组,并计算每个标签的商品的总销售额:

{ _id: "writing", totalSalesAmount: Decimal128("60.00") }{ _id: "stationary", totalSalesAmount: Decimal128("264.45") }{ _id: "electronics", totalSalesAmount: Decimal128("800.00") }{ _id: "school", totalSalesAmount: Decimal128("104.85") }{ _id: "office", totalSalesAmount: Decimal128("1019.60") }

要学习;了解有关相关方法的更多信息,请参阅 $group、$sum 和 $multiply 指南。

要查看如何在完整示例中使用$unwind,请参阅展开数组和分组数据教程。