$count 연산자는 지정된 쿼리 필터와 일치하는 문서 수를 계산하는 데 사용됩니다. count 연산자는 데이터를 요약하거나 특정 그룹화에 대한 개수를 생성하는 데 유용합니다.
Syntax
{
$count: "<fieldName>"
}
Parameters
| Parameter | Description |
|---|---|
<fieldName> |
개수가 저장될 출력 문서의 필드 이름입니다. |
Examples
스토어 컬렉션에서 이 샘플 문서를 고려합니다.
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
예제 1: 모든 문서 수 검색
컬렉션 내의 문서 수를 검색하려면 쿼리 필터 없이 개수 쿼리를 실행하기만 하면 됩니다.
db.stores.aggregate([{
$count: "totalDocuments"
}])
이 쿼리는 다음 결과를 반환합니다.
[
{
"totalDocuments": 41501
}
]
예제 2: 특정 필드별로 그룹화된 문서 개수 계산
각 판매 범주 내의 문서 수를 검색하려면 먼저 쿼리를 실행하여 판매 범주별로 문서를 그룹화합니다. 그런 다음 각 범주 내에서 개수 쿼리를 실행합니다.
db.stores.aggregate([{
$unwind: "$sales.salesByCategory"
},
{
$group: {
_id: "$sales.salesByCategory.categoryName",
totalCount: {
$count: {}
}
}
}
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"_id": "Christmas Trees",
"totalCount": 93
},
{
"_id": "Nuts",
"totalCount": 83
},
{
"_id": "Camping Tables",
"totalCount": 130
},
{
"_id": "Music Theory Books",
"totalCount": 52
},
{
"_id": "Fortified Wine",
"totalCount": 55
},
{
"_id": "Children's Mystery",
"totalCount": 45
},
{
"_id": "Short Throw Projectors",
"totalCount": 72
},
{
"_id": "Pliers",
"totalCount": 56
},
{
"_id": "Bluetooth Headphones",
"totalCount": 104
},
{
"_id": "Video Storage",
"totalCount": 80
},
{
"_id": "Cleansers",
"totalCount": 68
},
{
"_id": "Camera Straps",
"totalCount": 64
},
{
"_id": "Carry-On Bags",
"totalCount": 57
},
{
"_id": "Disinfectant Wipes",
"totalCount": 85
},
{
"_id": "Insignia Smart TVs",
"totalCount": 81
},
{
"_id": "Toner Refill Kits",
"totalCount": 38
},
{
"_id": "iPads",
"totalCount": 51
},
{
"_id": "Memory Foam Mattresses",
"totalCount": 58
},
{
"_id": "Storage Baskets",
"totalCount": 68
},
{
"_id": "Body Spray",
"totalCount": 96
}
]
예제 3: 승격 이벤트 수 계산
모든 저장소의 승격 이벤트 수를 계산하려면 먼저 쿼리를 실행하여 먼저 승격 이벤트로 해제한 다음 고유한 승격 이벤트를 계산합니다.
db.stores.aggregate([{
$unwind: "$promotionEvents"
},
{
$count: "totalPromotionEvents"
}
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"totalPromotionEvents": 145673
}
]
예제 4: 사용 $count$setWindowFields
매장당 노트북 프로모션 판매를 받으려면 먼저 쿼리를 실행하여 2023년에 랩톱의 프로모션 이벤트를 필터링합니다. 그런 다음 결과 저장소를 회사별로 분할합니다. 마지막으로 분할된 저장소에서 개수 쿼리를 실행하여 결과를 반환합니다.
db.stores.aggregate([{
$unwind: "$promotionEvents"
},
{
$unwind: "$promotionEvents.discounts"
},
// Filter only for Laptop discounts in 2023
{
$match: {
"promotionEvents.promotionalDates.startDate.Year": 2023,
"promotionEvents.discounts.categoryName": "Laptops"
}
},
// Add sales count by city using window function
{
$setWindowFields: {
partitionBy: "$company",
output: {
salesCount: {
$count: {},
window: {
documents: ["unbounded", "unbounded"]
}
}
}
}
},
// Group to return a single result per city
{
$group: {
_id: "$company",
salesCount: {
$first: "$salesCount"
}
}
}
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"_id": "VanArsdel, Ltd.",
"salesCount": 13
},
{
"_id": "Proseware, Inc.",
"salesCount": 12
},
{
"_id": "Fabrikam, Inc.",
"salesCount": 11
},
{
"_id": "Contoso, Ltd.",
"salesCount": 13
},
{
"_id": "Fourth Coffee",
"salesCount": 8
},
{
"_id": "Trey Research",
"salesCount": 14
},
{
"_id": "Adatum Corporation",
"salesCount": 12
},
{
"_id": "Relecloud",
"salesCount": 16
},
{
"_id": "Lakeshore Retail",
"salesCount": 13
},
{
"_id": "Northwind Traders",
"salesCount": 5
},
{
"_id": "First Up Consultants",
"salesCount": 4
},
{
"_id": "Wide World Importers",
"salesCount": 7
},
{
"_id": "Tailwind Traders",
"salesCount": 12
}
]
관련 콘텐츠
- MongoDB에서 Azure Cosmos DB for MongoDB(vCore)로 마이그레이션하기 위한 옵션을 검토합니다.
- MongoDB와의 기능 호환성에 대해 자세히 알아보세요.