

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

# $bucketAuto
<a name="bucketAuto"></a>

버전 8.0.2에서 새로 추가되었습니다.

Amazon DocumentDB의 `$bucketAuto` 집계 단계는 지정된 표현식을 기반으로 입력 문서를 지정된 수의 버킷으로 자동으로 그룹화합니다. 버킷 경계를 명시적으로 정의하는와 달리 `$bucket`는 문서가 요청된 버킷 수에 최대한 균등하게 배포되도록 경계를 `$bucketAuto` 자동으로 결정합니다. 이는 값의 분포를 미리 모르고 데이터를 고정된 수의 그룹으로 분류하려는 경우에 유용할 수 있습니다.

**파라미터**
+ `groupBy` (필수): 그룹화할 값을 지정하는 표현식입니다.
+ `buckets` (필수): 문서가 그룹화되는 버킷 수를 지정하는 양의 정수입니다. 입력 문서와 `groupBy` 표현식에 따라 실제 버킷 수는 지정된 수보다 적을 수 있습니다.
+ `output` (선택 사항): 각 버킷에 대해 출력할 정보를 지정하는 객체입니다. `$sum`, `$avg``$min`, 및 같은 누적기 연산자를 사용하여 각 버킷에 대한 집계를 계산`$max`할 수 있습니다. 생략하면 각 버킷은 기본적으로 `count` 필드를 출력합니다.
+ `granularity` (선택 사항): 버킷 경계에 사용할 기본 숫자 시리즈를 지정하는 문자열입니다. 이렇게 하면 계산된 경계가 표준 수치적 진행에 맞춰집니다. 이 파라미터는 모든 `groupBy` 값이 숫자이고 모두 인 경우에만 사용할 수 있습니다`NaN`. 유효한 값은 `R5`, , `R10`, `R20``R40`, `R80`, , `1-2-5`, `E6`, `E12`, `E24``E48`, `E96`, 및 `E192`입니다`POWERSOF2`.

**출력**

각 버킷은 버킷의 경계를 설명하는 `_id` 객체가 포함된 별도의 문서로 반환됩니다.
+ `_id.min`: 버킷의 포함 하한입니다.
+ `_id.max`: 버킷의 상한입니다. 이 바인딩은 포함된 시리즈의 최종 버킷을 제외한 모든 버킷에 대해 제외됩니다.

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

다음 예제에서는 `$bucketAuto` 스테이지를 사용하여 판매 데이터를 가격별로 버킷으로 그룹화하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.sales.insertMany([
  { item: "abc", price: 10, quantity: 2, date: new Date("2020-09-01") },
  { item: "def", price: 20, quantity: 1, date: new Date("2020-10-01") },
  { item: "ghi", price: 5, quantity: 3, date: new Date("2020-11-01") },
  { item: "jkl", price: 15, quantity: 2, date: new Date("2020-12-01") },
  { item: "mno", price: 25, quantity: 1, date: new Date("2021-01-01") }
]);
```

**쿼리 예제**

다음 명령은 샘플 문서를 가격별로 세 개의 버킷으로 그룹화합니다.

```
db.sales.aggregate([
  {
    $bucketAuto: {
      groupBy: "$price",
      buckets: 3,
      output: {
        "count": { $sum: 1 },
        "totalQuantity": { $sum: "$quantity" }
      }
    }
  }
])
```

**출력**

명령은 다음 출력을 반환합니다.

```
[
  { _id: { min: 5, max: 15 }, count: 2, totalQuantity: 5 },
  { _id: { min: 15, max: 25 }, count: 2, totalQuantity: 3 },
  { _id: { min: 25, max: 25 }, count: 1, totalQuantity: 1 }
]
```

**세분화된 쿼리 예제**

다음 예제에서는 계산된 버킷 경계를 2의 출력에 맞추는 `granularity` 옵션을 추가합니다.

```
db.sales.aggregate([
  {
    $bucketAuto: {
      groupBy: "$price",
      buckets: 2,
      granularity: "POWERSOF2",
      output: {
        "count": { $sum: 1 },
        "totalQuantity": { $sum: "$quantity" }
      }
    }
  }
])
```

**출력**

명령은 다음 출력을 반환합니다.

```
[
  { _id: { min: 4, max: 16 }, count: 3, totalQuantity: 7 },
  { _id: { min: 16, max: 32 }, count: 2, totalQuantity: 2 }
]
```

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

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

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

  const result = await sales.aggregate([
    {
      $bucketAuto: {
        groupBy: "$price",
        buckets: 3,
        output: {
          "count": { $sum: 1 },
          "totalQuantity": { $sum: "$quantity" }
        }
      }
    }
  ]).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']
    sales = db['sales']

    result = list(sales.aggregate([
        {
            '$bucketAuto': {
                'groupBy': '$price',
                'buckets': 3,
                'output': {
                    'count': {'$sum': 1},
                    'totalQuantity': {'$sum': '$quantity'}
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------