

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

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

`$unwind` 演算子は、入力ドキュメントから配列フィールドを分解して、各要素のドキュメントを出力するために使用されます。これは、データのフィルタリング、ソート、変換など、配列の個々の要素に対してオペレーションを実行する場合に便利です。

**パラメータ**
+ `path`: 巻き出す配列フィールドへのパス。
+ `includeArrayIndex`: (オプション) 配列要素のインデックスを保持する新しいフィールドの名前を指定します。
+ `preserveNullAndEmptyArrays`: (オプション) 配列フィールドが null または空の配列の場合、オペレーションが元のドキュメントを保持するかどうかを決定します。

## 例 (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()
```

------