Aggregate.unwind(value: string|object): Aggregate
聚合阶段。使用指定的数组字段中的每个元素,对文档进行拆分。拆分后,文档会从一个变为一个或多个,分别对应数组的每个元素。
Aggregate
使用指定的数组字段中的每个元素,对文档进行拆分。拆分后,文档会从一个变为一个或多个,分别对应数组的每个元素。
有两种使用形式:
- 参数是一个字段名
- 参数是一个对象
unwind({
path: <字段名>,
includeArrayIndex: <string>,
})
拆分数组
{ "_id": "1", "product": "tshirt", "size": ["S", "M", "L"] }
{ "_id": "3", "product": "socks", "size": null }
{ "_id": "4", "product": "trousers", "size": ["S"] }
{ "_id": "5", "product": "sweater", "size": ["M", "L"] }
我们根据 size
字段对这些文档进行拆分
输出如下:
{ "_id": "1", "product": "tshirt", "size": "S" }
{ "_id": "1", "product": "tshirt", "size": "M" }
{ "_id": "1", "product": "tshirt", "size": "L" }
{ "_id": "4", "product": "trousers", "size": "S" }
{ "_id": "5", "product": "sweater", "size": "M" }
{ "_id": "5", "product": "sweater", "size": "L" }
拆分后,保留原数组的索引
我们根据 size
字段对文档进行拆分后,想要保留原数组索引在新的 index
字段中。
db.collection('products')
.aggregate()
includeArrayIndex: 'index'
})
.end()
保留字段为空的文档
注意到我们的集合中有两行特殊的空值数据:
...
{ "_id": "2", "product": "pants", "size": [] }
{ "_id": "3", "product": "socks", "size": null }
...
如果想要在输出中保留 size
为空数组、null,或者 size
字段不存在的文档,可以使用 preserveNullAndEmptyArrays
参数
db.collection('products')
.aggregate()
.unwind({
path: '$size',
preserveNullAndEmptyArrays: true
输出如下: