View a markdown version of this page

$count (Akkumulator) - Amazon DocumentDB

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

$count (Akkumulator)

Neu ab Version 8.0.1.

Verwenden Sie den $count Akkumulator innerhalb einer $group Stufe, um die Anzahl der Dokumente in jeder Gruppe zurückzugeben. Es akzeptiert ein leeres Objekt {} als Argument.

Dies unterscheidet sich von der $count Pipeline-Phase, bei der es sich um eine eigenständige Phase handelt, in der alle Dokumente gezählt werden, die die Pipeline durchlaufen. Der $count Akkumulator zählt stattdessen die Dokumente innerhalb jeder Gruppe, die von $group erstellt wurde.

Syntax

{ $count: {} }

Parameter

  • Der $count Akkumulator akzeptiert keine Argumente. Er akzeptiert ein leeres Objekt {} und gibt die Anzahl der Dokumente in jeder Gruppe zurück.

Beispiel (MongoDB Shell)

Das folgende Beispiel zeigt, wie der $count Akkumulator verwendet wird, um die Anzahl der Produkte in jeder Kategorie zu zählen.

Erstellen Sie Beispieldokumente

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

Beispiel für eine Abfrage

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

Ausgabe

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

Beispiel für die Verwendung von Fensteroperatoren (MongoDB Shell)

Neu ab Version 8.0.2.

Der $count Akkumulator kann auch als Fensterantrieb auf der $setWindowFields Bühne verwendet werden. In diesem Zusammenhang gibt es die Anzahl der Dokumente in jedem Fenster zurück. Sie geben den Operator unter dem output Feld an und definieren optional die Fenstergrenzen mit einem window Dokument.

Erstellen Sie Beispieldokumente

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

Beispiel für eine Abfrage

Das folgende Beispiel partitioniert die Dokumente nachcategory, sortiert jede Partition nach day und gibt eine fortlaufende Anzahl von Dokumenten vom Anfang der Partition bis zum aktuellen Dokument zurück.

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

Ausgabe

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

Jedes Dokument wird um die Anzahl der Dokumente in seiner Partition bis einschließlich des aktuellen Dokuments erweitert. runningCount

Codebeispiele

Um ein Codebeispiel für die Verwendung des $count Akkumulators anzuzeigen, wählen Sie die Registerkarte für die Sprache, die Sie verwenden möchten. Die folgenden Beispiele zeigen sowohl die Verwendung des Akkumulators (in$group) als auch die Verwendung von Fensteroperatoren (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()