View a markdown version of this page

$count (akumulator) - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$count (akumulator)

Baru dari versi 8.0.1.

Gunakan $count akumulator dalam $group tahap untuk mengembalikan jumlah dokumen di setiap grup. Ia menerima objek kosong {} sebagai argumennya.

Ini berbeda dengan tahap $count pipeline, yang merupakan tahap mandiri yang menghitung semua dokumen yang melewati pipa. A $count kumulator malah menghitung dokumen dalam setiap kelompok yang diproduksi oleh$group.

Sintaksis

{ $count: {} }

Parameter

  • A $count kumulator tidak membutuhkan argumen. Ini menerima objek kosong {} dan mengembalikan jumlah dokumen di setiap grup.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $count akumulator untuk menghitung jumlah produk di setiap kategori.

Buat dokumen sampel

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

Contoh kueri

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

Keluaran

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

Contoh penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

A $count kumulator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan jumlah dokumen di setiap jendela. Anda menentukan operator di bawah output bidang, dan secara opsional menentukan batas jendela dengan window dokumen.

Buat dokumen sampel

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 } ])

Contoh kueri

Contoh berikut mempartisi dokumen berdasarkancategory, mengurutkan setiap partisi berdasarkanday, dan mengembalikan jumlah dokumen yang berjalan dari awal partisi melalui dokumen saat ini.

db.events.aggregate([ { $setWindowFields: { partitionBy: "$category", sortBy: { day: 1 }, output: { runningCount: { $count: {}, window: { documents: ["unbounded", "current"] } } } } } ])

Keluaran

[ { "_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 } ]

Setiap dokumen ditambah denganrunningCount, jumlah dokumen dalam partisinya hingga dan termasuk dokumen saat ini.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $count akumulator, pilih tab untuk bahasa yang ingin Anda gunakan. Contoh berikut menunjukkan penggunaan akumulator (in$group) dan penggunaan operator jendela (in$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()