

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

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

Amazon DocumentDB의 `$setUnion` 집계 연산자는 두 개 이상의 값 세트를 결합하고 입력 세트의 모든 고유 요소가 포함된 세트를 반환하는 데 사용됩니다. 이 연산자는 문서의 배열 필드에 대해 설정 기반 작업을 수행해야 할 때 유용합니다.

**파라미터**
+ `expression1`: 배열로 확인되는 표현식입니다.
+ `expression2`: 배열로 확인되는 표현식입니다.
+ `expressionN`: 배열로 확인되는 추가 표현식(선택 사항).

## 예제(MongoDB 쉘)
<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()
```

------