View a markdown version of this page

$count (アキュムレータ) - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$count (アキュムレータ)

バージョン 8.0.1 から新規。

$group ステージ内の$countアキュムレータを使用して、各グループのドキュメント数を返します。引数{}として空のオブジェクトを受け入れます。

これは、$countパイプラインを通過するすべてのドキュメントをカウントするスタンドアロンステージであるパイプラインステージとは異なります。アキュムレータは代わりに$count、 によって生成された各グループ内のドキュメントをカウントします$group

[Syntax] (構文)

{ $count: {} }

パラメータ

  • $count アキュムレータは引数を取りません。空のオブジェクトを受け入れ{}、各グループのドキュメントの数を返します。

例 (MongoDB シェル)

次の例は、 $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 } ]

コードの例

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