

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

# \$1size
<a name="size-query"></a>

`$size` 쿼리 연산자는 배열 필드의 요소 수가 정확히 지정된 문서와 일치합니다. 이는 배열 길이를 기준으로 문서를 필터링하는 데 유용합니다.

**파라미터**
+ `field`: 확인할 배열 필드입니다.
+ `count`: 배열에 포함되어야 하는 정확한 요소 수입니다.

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

다음 예제에서는 `$size` 연산자를 사용하여 정확히 세 개의 태그가 있는 모든 제품을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] },
  { _id: 2, name: "Mouse", tags: ["electronics", "accessories"] },
  { _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] },
  { _id: 4, name: "Monitor", tags: ["electronics"] }
]);
```

**쿼리 예제**

```
db.products.find({ tags: { $size: 3 } });
```

**출력**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

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

`$size` 쿼리 연산자를 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

  const result = await collection.find({ tags: { $size: 3 } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  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']
    collection = db['products']

    result = list(collection.find({'tags': {'$size': 3}}))

    print(result)
    client.close()

example()
```

------