$count - Amazon DocumentDB

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

$count

Amazon DocumentDB의 $count 집계 단계는가 단계로 전달하는 문서 수를 계산하는 데 사용됩니다. 집계 파이프라인의 최종 단계로 사용되어 이전 단계와 일치하는 총 문서 수를 반환하는 경우가 많습니다.

파라미터

  • field: 계산할 필드입니다. 이 파라미터는 선택 사항이며 제공되지 않은 경우 스테이지는 총 입력 문서 수를 계산합니다.

예제(MongoDB 쉘)

다음 예제에서는 $count 스테이지를 사용하여 컬렉션의 총 문서 수를 가져오는 방법을 보여줍니다.

샘플 문서 생성

db.users.insertMany([ { name: "John", age: 30 }, { name: "Jane", age: 25 }, { name: "Bob", age: 35 }, { name: "Alice", age: 28 } ]);

쿼리 예제

db.users.aggregate([ { $count: "total" } ]);

출력

{ "total" : 4 }

이 예제에서는 users 컬렉션을 집계하고 $count 스테이지를 사용하여 총 문서 수를 계산합니다.

코드 예제

$count 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

Node.js
const { MongoClient } = require('mongodb'); async function countDocuments() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('mydb'); const collection = db.collection('users'); const result = await collection.aggregate([ { $count: "total" } ]).toArray(); console.log(result[0].total); await client.close(); } countDocuments();
Python
from pymongo import MongoClient def count_documents(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['mydb'] collection = db['users'] result = list(collection.aggregate([ { '$count': "total" } ])) print(result[0]['total']) client.close() count_documents()