

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

------