

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

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

Amazon DocumentDB의 `$setIntersection` 연산자는 두 개 이상의 배열 간에 공통 요소를 반환하는 데 사용됩니다. 이 연산자는 데이터 세트로 작업할 때 특히 유용하므로 여러 세트의 교차점을 찾을 수 있습니다.

**파라미터**
+ `array1`: 교차할 첫 번째 배열입니다.
+ `array2`: 교차할 두 번째 배열입니다.
+ `arrayN`: (선택 사항) 교차할 추가 배열입니다.

## 예제(MongoDB 쉘)
<a name="setIntersection-examples"></a>

다음 예제에서는 `$setIntersection` 연산자를 사용하여 두 배열 간의 공통 요소를 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.collection.insertMany([
  { _id: 1, colors: ["red", "blue", "green"] },
  { _id: 2, colors: ["blue", "yellow", "orange"] },
  { _id: 3, colors: ["red", "green", "purple"] }
])
```

**쿼리 예제**

```
db.collection.aggregate([
  { $project: {
      _id: 1,
      commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
    }
  }
])
```

**출력**

```
[
  { "_id": 1, "commonColors": ["red", "blue", "green"] },
  { "_id": 2, "commonColors": ["blue"] },
  { "_id": 3, "commonColors": ["red", "green"] }
]
```

## 코드 예제
<a name="setIntersection-code"></a>

`$setIntersection` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ 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('mycollection');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] }
      }
    }
  ]).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['mycollection']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'commonColors': { '$setIntersection': ["$colors", ["red", "blue", "green"]] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------