View a markdown version of this page

$count(누적기) - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$count(누적기)

버전 8.0.1에서 새로 추가되었습니다.

$group 단계 내의 $count 누적기를 사용하여 각 그룹의 문서 수를 반환합니다. 빈 객체를 인수{}로 허용합니다.

이는 $count 파이프라인을 통과하는 모든 문서를 계산하는 독립 실행형 단계인 파이프라인 단계와 다릅니다. 대신 누적기는 $count에서 생성한 각 그룹 내의 문서를 계산합니다$group.

구문

{ $count: {} }

파라미터

  • $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 } ]

코드 예제

$count 누적기 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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'); const collection = db.collection('products'); const result = await collection.aggregate([ { $group: { _id: "$category", count: { $count: {} } } } ]).toArray(); console.log(result); } 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'] collection = db['products'] result = list(collection.aggregate([ { '$group': { '_id': '$category', 'count': { '$count': {} } } } ])) pprint(result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()