

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

# $count （累積器）
<a name="count-accumulator"></a>

8.0.1 版的新功能。

使用`$group`階段內的`$count`累積器來傳回每個群組中的文件數量。它接受空物件`{}`做為其引數。

這與`$count`管道階段不同，這是一個獨立的階段，可計算通過管道的所有文件。`$count` 累積器會改為計算 產生的每個群組中的文件`$group`。

**語法**

```
{ $count: {} }
```

**參數**
+ `$count` 累積器不採用任何引數。它接受空物件，`{}`並傳回每個群組中的文件計數。

## 範例 (MongoDB Shell)
<a name="count-accumulator-examples"></a>

下列範例顯示如何使用`$count`累積器計算每個類別中的產品數量。

**建立範例文件**

```
db.products.insertMany([
  { name: "Widget", category: "A" },
  { name: "Gadget", category: "A" },
  { name: "Doohickey", category: "B" },
  { name: "Thingamajig", category: "B" },
  { name: "Whatsit", category: "B" }
])
```

**查詢範例**

```
db.products.aggregate([
  { $group: { _id: "$category", count: { $count: {} } } }
])
```

**輸出**

```
[
  { "_id": "A", "count": 2 },
  { "_id": "B", "count": 3 }
]
```

## 程式碼範例
<a name="count-accumulator-code"></a>

若要檢視使用`$count`累積器的程式碼範例，請選擇您要使用的語言標籤：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('products');

    const result = await collection.aggregate([
      { $group: { _id: "$category", count: { $count: {} } } }
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
from pprint import pprint

def example():
    client = None
    try:
        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.aggregate([
            { '$group': { '_id': '$category', 'count': { '$count': {} } } }
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------