

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1unwind
<a name="unwind"></a>

该`$unwind`运算符用于从输入文档中解构一个数组字段，为每个元素输出一个文档。当您要对数组的各个元素执行操作（例如筛选、排序或转换数据）时，这可能很有用。

**参数**
+ `path`: 要展开的数组字段的路径。
+ `includeArrayIndex`:（可选）指定用于保存数组元素索引的新字段的名称。
+ `preserveNullAndEmptyArrays`:（可选）确定当数组字段为空还是空数组时，操作是保留原始文档。

## 示例（MongoDB 外壳）
<a name="unwind-examples"></a>

以下示例演示如何使用`$unwind`运算符解构数组字段并对各个元素执行进一步的操作。

**创建示例文档**

```
db.people.insertMany([
  { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] },
  { _id: 2, name: "jane", hobbies: ["reading", "swimming"] },
  { _id: 3, name: "jack", hobbies: [] }
])
```

**查询示例**

```
db.people.aggregate([
  { $unwind: "$hobbies" }
])
```

**输出**

```
[
  { _id: 1, name: 'jon', hobbies: 'painting' },
  { _id: 1, name: 'jon', hobbies: 'dancing' },
  { _id: 1, name: 'jon', hobbies: 'singing' },
  { _id: 2, name: 'jane', hobbies: 'reading' },
  { _id: 2, name: 'jane', hobbies: 'swimming' }
]
```

## 代码示例
<a name="unwind-code"></a>

要查看使用该`$unwind`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('people');

  const result = await collection.aggregate([
    { $unwind: '$hobbies' }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['people']

    result = list(collection.aggregate([
        { '$unwind': '$hobbies' }
    ]))

    print(result)
    client.close()

example()
```

------