Aggregate.unwind(value: string|object): Aggregate

    聚合阶段。使用指定的数组字段中的每个元素,对文档进行拆分。拆分后,文档会从一个变为一个或多个,分别对应数组的每个元素。

    Aggregate

    使用指定的数组字段中的每个元素,对文档进行拆分。拆分后,文档会从一个变为一个或多个,分别对应数组的每个元素。

    有两种使用形式:

    • 参数是一个字段名
    • 参数是一个对象
    1. unwind({
    2. path: <字段名>,
    3. includeArrayIndex: <string>,
    4. })

    拆分数组

    1. { "_id": "1", "product": "tshirt", "size": ["S", "M", "L"] }
    2. { "_id": "3", "product": "socks", "size": null }
    3. { "_id": "4", "product": "trousers", "size": ["S"] }
    4. { "_id": "5", "product": "sweater", "size": ["M", "L"] }

    我们根据 size 字段对这些文档进行拆分

    输出如下:

    1. { "_id": "1", "product": "tshirt", "size": "S" }
    2. { "_id": "1", "product": "tshirt", "size": "M" }
    3. { "_id": "1", "product": "tshirt", "size": "L" }
    4. { "_id": "4", "product": "trousers", "size": "S" }
    5. { "_id": "5", "product": "sweater", "size": "M" }
    6. { "_id": "5", "product": "sweater", "size": "L" }

    拆分后,保留原数组的索引

    我们根据 size 字段对文档进行拆分后,想要保留原数组索引在新的 index 字段中。

    1. db.collection('products')
    2. .aggregate()
    3. includeArrayIndex: 'index'
    4. })
    5. .end()

    保留字段为空的文档

    注意到我们的集合中有两行特殊的空值数据:

    1. ...
    2. { "_id": "2", "product": "pants", "size": [] }
    3. { "_id": "3", "product": "socks", "size": null }
    4. ...

    如果想要在输出中保留 size 为空数组、null,或者 size 字段不存在的文档,可以使用 preserveNullAndEmptyArrays 参数

    1. db.collection('products')
    2. .aggregate()
    3. .unwind({
    4. path: '$size',
    5. preserveNullAndEmptyArrays: true

    输出如下: