$count

运算符 $count 用于计算与指定查询筛选器匹配的文档数。 count 运算符可用于汇总数据或生成特定分组的计数。

语法

{
    $count: "<fieldName>"
}

参数

参数 DESCRIPTION
<fieldName> 输出文档中将存储计数的字段的名称。

例子

请考虑存储集合中的此示例文档。

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