翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$count (アキュムレータ)
バージョン 8.0.1 の新機能。
$group ステージ内の$countアキュムレータを使用して、各グループのドキュメント数を返します。引数{}として空のオブジェクトを受け入れます。
これは、$countパイプラインを通過するすべてのドキュメントをカウントするスタンドアロンステージであるパイプラインステージとは異なります。アキュムレータは代わりに$count、 によって生成された各グループ内のドキュメントをカウントします$group。
[Syntax] (構文)
{ $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 }
]
ウィンドウ演算子の使用例 (MongoDB シェル)
バージョン 8.0.2 の新機能。
$count アキュムレータは、$setWindowFieldsステージのウィンドウ演算子としても使用できます。このコンテキストでは、各ウィンドウのドキュメント数を返します。output フィールドで 演算子を指定し、オプションでwindowドキュメントを使用してウィンドウの境界を定義します。
サンプルドキュメントを作成する
db.events.insertMany([
{ _id: 1, category: "A", day: 1 },
{ _id: 2, category: "A", day: 2 },
{ _id: 3, category: "A", day: 3 },
{ _id: 4, category: "B", day: 1 },
{ _id: 5, category: "B", day: 2 }
])
クエリの例
次の例ではcategory、ドキュメントを でパーティション化し、各パーティションを でソートしてday、パーティションの開始から現在のドキュメントまでのドキュメントの実行数を返します。
db.events.aggregate([
{
$setWindowFields: {
partitionBy: "$category",
sortBy: { day: 1 },
output: {
runningCount: {
$count: {},
window: { documents: ["unbounded", "current"] }
}
}
}
}
])
出力
[
{ "_id": 1, "category": "A", "day": 1, "runningCount": 1 },
{ "_id": 2, "category": "A", "day": 2, "runningCount": 2 },
{ "_id": 3, "category": "A", "day": 3, "runningCount": 3 },
{ "_id": 4, "category": "B", "day": 1, "runningCount": 1 },
{ "_id": 5, "category": "B", "day": 2, "runningCount": 2 }
]
各ドキュメントはrunningCount、現在のドキュメントまでのパーティション内のドキュメントの数である で拡張されます。
コードの例
$count アキュムレータを使用するためのコード例を表示するには、使用する言語のタブを選択します。次の例は、アキュムレータの使用 ( の場合$group) とウィンドウ演算子の使用 ( の場合) の両方を示しています$setWindowFields。
- 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');
// Accumulator usage: count per group
const products = db.collection('products');
await products.insertMany([
{ name: "Widget", category: "A" },
{ name: "Gadget", category: "A" },
{ name: "Doohickey", category: "B" },
{ name: "Thingamajig", category: "B" },
{ name: "Whatsit", category: "B" }
]);
const accumulatorResult = await products.aggregate([
{ $group: { _id: "$category", count: { $count: {} } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: running count within each partition
const events = db.collection('events');
await events.insertMany([
{ _id: 1, category: "A", day: 1 },
{ _id: 2, category: "A", day: 2 },
{ _id: 3, category: "A", day: 3 },
{ _id: 4, category: "B", day: 1 },
{ _id: 5, category: "B", day: 2 }
]);
const windowResult = await events.aggregate([
{
$setWindowFields: {
partitionBy: "$category",
sortBy: { day: 1 },
output: {
runningCount: {
$count: {},
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
} 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']
# Accumulator usage: count per group
products = db['products']
products.insert_many([
{ 'name': 'Widget', 'category': 'A' },
{ 'name': 'Gadget', 'category': 'A' },
{ 'name': 'Doohickey', 'category': 'B' },
{ 'name': 'Thingamajig', 'category': 'B' },
{ 'name': 'Whatsit', 'category': 'B' }
])
accumulator_result = list(products.aggregate([
{ '$group': { '_id': '$category', 'count': { '$count': {} } } }
]))
pprint(accumulator_result)
# Window operator usage: running count within each partition
events = db['events']
events.insert_many([
{ '_id': 1, 'category': 'A', 'day': 1 },
{ '_id': 2, 'category': 'A', 'day': 2 },
{ '_id': 3, 'category': 'A', 'day': 3 },
{ '_id': 4, 'category': 'B', 'day': 1 },
{ '_id': 5, 'category': 'B', 'day': 2 }
])
window_result = list(events.aggregate([
{
'$setWindowFields': {
'partitionBy': '$category',
'sortBy': { 'day': 1 },
'output': {
'runningCount': {
'$count': {},
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
pprint(window_result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()