$count

Der $count Operator wird verwendet, um die Anzahl der Dokumente zu zählen, die einem angegebenen Abfragefilter entsprechen. Der Zählungsoperator eignet sich zum Zusammenfassen von Daten oder zum Generieren von Zählungen für bestimmte Gruppierungen.

Syntax

{
    $count: "<fieldName>"
}

Die Parameter

Parameter Description
<fieldName> Der Name des Felds im Ausgabedokument, in dem die Anzahl gespeichert wird.

Examples

Betrachten Sie dieses Beispieldokument aus der Stores-Sammlung.

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

Beispiel 1: Abrufen der Anzahl aller Dokumente

Um die Anzahl der Dokumente in der Auflistung abzurufen, führen Sie einfach eine Anzahlabfrage ohne Abfragefilter aus.

db.stores.aggregate([{
    $count: "totalDocuments"
}])

Diese Abfrage gibt das folgende Ergebnis zurück:

[
    {
        "totalDocuments": 41501
    }
]

Beispiel 2: Zählen von Dokumenten, die nach einem bestimmten Feld gruppiert sind

Um die Anzahl der Dokumente in jeder Vertriebskategorie abzurufen, führen Sie zuerst eine Abfrage aus, um Dokumente nach Verkaufskategorie zu gruppieren. Führen Sie dann eine Anzahlabfrage in jeder Kategorie aus.

db.stores.aggregate([{
        $unwind: "$sales.salesByCategory"
    },
    {
        $group: {
            _id: "$sales.salesByCategory.categoryName",
            totalCount: {
                $count: {}
            }
        }
    }
])

Diese Abfrage gibt die folgenden Ergebnisse zurück:

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

Beispiel 3: Zählen der Anzahl der Heraufstufungsereignisse

Um die Anzahl der Promotion-Ereignisse in allen Stores zu zählen, führen Sie zunächst eine Abfrage aus, um sich zuerst durch Promotion-Ereignisse zu entspannen und dann die unterschiedlichen Werbeaktionsereignisse zu zählen.

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $count: "totalPromotionEvents"
    }
])

Diese Abfrage gibt das folgende Ergebnis zurück:

[
    {
        "totalPromotionEvents": 145673
    }
]

Beispiel 4: Verwenden $count in $setWindowFields

Um Umsätze für Laptops-Werbeaktionen pro Store zu erhalten, führen Sie zunächst eine Abfrage aus, um Werbeereignisse für Laptops im Jahr 2023 zu filtern. Partitionieren Sie dann die resultierenden Speicher nach Unternehmen. Führen Sie schließlich eine Anzahlabfrage in den partitionierten Speicher aus, um die Ergebnisse zurückzugeben.

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"
            }
        }
    }
])

Diese Abfrage gibt die folgenden Ergebnisse zurück:

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