

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

Amazon DocumentDB `$setUnion` 中的彙總運算子用於結合兩組或多組值，並傳回包含輸入集中所有唯一元素的集合。當您需要對文件中的陣列欄位執行設定型操作時，此運算子非常有用。

**參數**
+ `expression1`：解析為陣列的表達式。
+ `expression2`：解析為陣列的表達式。
+ `expressionN`：解析為陣列的其他表達式 （選用）。

## 範例 (MongoDB Shell)
<a name="setUnion-examples"></a>

下列範例示範如何使用 `$setUnion`運算子來結合集合中兩個陣列欄位的唯一元素。

**建立範例文件**

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

------