View a markdown version of this page

$count (accumulatore) - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$count (accumulatore)

Nuovo dalla versione 8.0.1.

Utilizza l'$countaccumulatore in una $group fase per restituire il numero di documenti in ciascun gruppo. Accetta un oggetto vuoto {} come argomento.

Questa è diversa dalla fase della $count pipeline, che è una fase autonoma che conta tutti i documenti che passano attraverso la pipeline. L'$countaccumulatore conta invece i documenti all'interno di ciascun gruppo prodotto da. $group

Sintassi

{ $count: {} }

Parametri

  • L'$countaccumulatore non accetta argomenti. Accetta un oggetto vuoto {} e restituisce il numero di documenti in ogni gruppo.

Esempio (MongoDB Shell)

L'esempio seguente mostra come utilizzare l'$countaccumulatore per contare il numero di prodotti in ciascuna categoria.

Crea documenti di esempio

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

Esempio di interrogazione

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

Output

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

Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)

Nuovo dalla versione 8.0.2.

L'$countaccumulatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce il numero di documenti in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.

Create documenti di esempio

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

Esempio di interrogazione

L'esempio seguente suddivide i documenti in basecategory, ordina ogni partizione in base day e restituisce un numero progressivo di documenti dall'inizio della partizione fino al documento corrente.

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

Output

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

A ogni documento viene aggiunto il numero di documenti all'interno della relativa partizione fino al documento corrente incluso. runningCount

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo dell'$countaccumulatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo dell'accumulatore (in$group) che l'utilizzo dell'operatore di finestra (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()