View a markdown version of this page

$sortByCount - Amazon DocumentDB

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

$sortByCount

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

Amazon DocumentDB의 $sortByCount 집계 단계는 지정된 표현식의 값을 기준으로 수신 문서를 그룹화한 다음 각 고유 그룹의 문서 수를 계산하고 내림차순으로 개수를 기준으로 결과를 정렬합니다. 이는 $sum 누적기가 있는 $group 단계와 동일하며 개수 필드에 $sort 단계가 있습니다.

파라미터

  • expression: 그룹화 기준의 표현식입니다. 필드 경로( 접두사 $) 또는 유효한 집계 표현식일 수 있습니다.

예제(MongoDB 쉘)

다음 예제에서는 $sortByCount 스테이지를 사용하여 범주 필드별로 문서를 계산하고 정렬하는 방법을 보여줍니다.

샘플 문서 생성

db.products.insertMany([ { name: "Widget", category: "electronics" }, { name: "Gadget", category: "electronics" }, { name: "Doohickey", category: "electronics" }, { name: "Apple", category: "food" }, { name: "Banana", category: "food" }, { name: "Hammer", category: "tools" } ]);

쿼리 예제

db.products.aggregate([ { $sortByCount: "$category" } ]);

출력

[ { "_id": "electronics", "count": 3 }, { "_id": "food", "count": 2 }, { "_id": "tools", "count": 1 } ]

결과는 내림차순으로 count에 따라 자동으로 정렬됩니다.

코드 예제

$sortByCount 스테이지 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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