

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

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

Amazon DocumentDB の`$setUnion`集計演算子は、2 つ以上の値のセットを組み合わせて、入力セットのすべての一意の要素を含むセットを返すために使用されます。この演算子は、ドキュメントの配列フィールドに対してセットベースのオペレーションを実行する必要がある場合に便利です。

**パラメータ**
+ `expression1`: 配列に解決される式。
+ `expression2`: 配列に解決される式。
+ `expressionN`: 配列に解決される追加の式 (オプション）。

## 例 (MongoDB シェル)
<a name="setUnion-examples"></a>

次の例は、 `$setUnion`演算子を使用して、コレクション内の 2 つの配列フィールドの一意の要素を組み合わせる方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { _id: 1, name: "Alice", hobbies: ["reading", "swimming"], skills: ["coding", "writing"] },
  { _id: 2, name: "Bob", hobbies: ["cooking", "gardening"], skills: ["coding", "photography"] },
  { _id: 3, name: "Charlie", hobbies: ["reading", "painting"], skills: ["gardening", "music"] }
]);
```

**クエリの例**

```
db.users.aggregate([
  {
    $project: {
      name: 1,
      allInterests: { $setUnion: ["$hobbies", "$skills"] }
    }
  }
]);
```

**出力**

```
[
  { "_id" : 1, "name" : "Alice", "allInterests" : [ "coding", "reading", "swimming", "writing" ] },
  { "_id" : 2, "name" : "Bob", "allInterests" : [ "coding", "cooking", "gardening", "photography" ] },
  { "_id" : 3, "name" : "Charlie", "allInterests" : [ "gardening", "music", "painting", "reading" ] }
]
```

この例では、 `$setUnion`演算子を使用して、各ユーザードキュメントの `hobbies`および `skills`配列フィールドの一意の要素を組み合わせます。結果の`allInterests`フィールドには、各ユーザーのすべての固有の趣味とスキルの結合が含まれます。

## コードの例
<a name="setUnion-code"></a>

`$setUnion` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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 users = db.collection('users');

  const result = await users.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
        allInterests: { $setUnion: ["$hobbies", "$skills"] }
      }
    }
  ]).toArray();

  console.log(result);
  await 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']
    users = db['users']

    result = list(users.aggregate([
        {
            '$project': {
                '_id': 1,
                'name': 1,
                'allInterests': { '$setUnion': ["$hobbies", "$skills"] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------