本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$count (累加器)
8.0.1 版的新功能。
$count 在$group階段內使用累積器來傳回每個群組中的文件數量。它接受空物件{}做為其引數。
這與$count管道階段不同,這是一個獨立的階段,可計算通過管道的所有文件。$count 累積器會改為計算 產生的每個群組中的文件$group。
語法
{ $count: {} }
參數
範例 (MongoDB Shell)
下列範例顯示如何使用$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 Shell)
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()