

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

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

8.0.2 版的新功能。

Amazon DocumentDB `$bucketAuto` 中的彙總階段會根據指定的表達式，自動將輸入文件分組到指定數量的儲存貯體中。與明確定義儲存貯體界限的 不同`$bucket`， `$bucketAuto`會自動決定邊界，以便盡可能平均地分配文件到請求的儲存貯體數量。當您想要將資料分類為固定數量的群組，而不事先知道值的分佈時，這會很有用。

**參數**
+ `groupBy` （必要）：指定要分組之值的表達式。
+ `buckets` （必要）：正整數，指定文件分組的儲存貯體數量。根據輸入文件和`groupBy`表達式，儲存貯體的實際數量可以小於指定的數量。
+ `output` （選用）：指定要為每個儲存貯體輸出資訊的物件。您可以使用累積器運算子，例如 `$sum`、`$min`、 `$avg`和 `$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 Shell)
<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 }
]
```

**具有精細度的查詢範例**

下列範例新增 `granularity`選項，將計算的儲存貯體邊界貼齊 2 的功率。

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

------