$topN

運算符 $topN 會根據查詢指定的一或多個字段排序檔,並傳回符合篩選準則的前 N 份檔。 它可讓您擷取多個最高排名的元素 (而不只是最高排名的單一項目),藉以擴充 $top 的功能。

語法

{
    $topN: {
        output: [listOfFields],
        sortBy: {
            <fieldName>: < sortOrder >
        },
        n: < numDocumentsToReturn >
    }
}

參數

參數 Description
listOfFields 要針對結果集中最後一份檔傳回的欄位清單
fieldName 用於排序結果集的欄位
sortOrder 1 或 -1。 1 表示以欄位值的遞增順序排序,而 -1 表示以欄位值的遞減順序排序
n 要從已排序結果集頂端傳回的檔數目

範例

請參考商店集合中的此範例檔。

{
    "_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 - 取得總銷售額最低的兩家商店

若要依第一個 Up 顧問公司內的銷售額取得兩個最低商店,請執行查詢以篩選公司名稱、依銷售遞增順序排序產生的檔,並從已排序的結果集中傳回前兩份檔。

db.stores.aggregate([{
    $match: {
        company: {
            $in: ["First Up Consultants"]
        }
    }
}, {
    $group: {
        _id: "$company",
        topSales: {
            $topN: {
                output: ["$company", "$sales"],
                sortBy: {
                    "sales.totalSales": 1
                },
                n: 2
            }
        }
    }
}])

此查詢會傳回下列結果:

[
    {
        "_id": "First Up Consultants",
        "topSales": [
            [
                "First Up Consultants",
                {
                    "salesByCategory": [
                        {
                            "categoryName": "Towel Sets",
                            "totalSales": 520
                        },
                        {
                            "categoryName": "Bath Accessories",
                            "totalSales": 41710
                        },
                        {
                            "categoryName": "Drapes",
                            "totalSales": 42893
                        },
                        {
                            "categoryName": "Towel Racks",
                            "totalSales": 30773
                        },
                        {
                            "categoryName": "Hybrid Mattresses",
                            "totalSales": 39491
                        },
                        {
                            "categoryName": "Innerspring Mattresses",
                            "totalSales": 6410
                        },
                        {
                            "categoryName": "Bed Frames",
                            "totalSales": 41917
                        },
                        {
                            "categoryName": "Mattress Protectors",
                            "totalSales": 44124
                        },
                        {
                            "categoryName": "Bath Towels",
                            "totalSales": 5671
                        },
                        {
                            "categoryName": "Turkish Towels",
                            "totalSales": 25674
                        }
                    ],
                    "revenue": 279183
                }
            ],
            [
                "First Up Consultants",
                {
                    "salesByCategory": [
                        {
                            "categoryName": "Lavalier Microphones",
                            "totalSales": 40000
                        },
                        {
                            "categoryName": "Wireless Microphones",
                            "totalSales": 39691
                        }
                    ],
                    "minimumSalesTarget": 30000,
                    "revenue": 50000
                }
            ]
        ]
    }
]

範例 2:取得最近兩個促銷事件

若要尋找每個市集最近的兩個促銷事件,請依市集將檔分組在集合中,依促銷日期的遞增順序排序,並從每個存放區排序結果集的前兩個結果。

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $group: {
            _id: "$_id",
            storeName: {
                $first: "$name"
            },
            top2RecentPromotions: {
                $topN: {
                    n: 2,
                    sortBy: {
                        "promotionEvents.promotionalDates.startDate.Year": -1,
                        "promotionEvents.promotionalDates.startDate.Month": -1,
                        "promotionEvents.promotionalDates.startDate.Day": -1
                    },
                    output: {
                        eventName: "$promotionEvents.eventName",
                        startDate: "$promotionEvents.promotionalDates.startDate"
                    }
                }
            }
        }
    }
])

此查詢傳回的前兩個結果是:

[
    {
        "_id": "4a99546f-a1d2-4e61-ae9f-b8c7c1faf73c'",
        "storeName": "Lakeshore Retail | Stationery Nook - West Van",
        "top2RecentPromotions": [
            {
                "eventName": "Crazy Markdown Madness",
                "startDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 21
                }
            },
            {
                "eventName": "Flash Sale Fiesta",
                "startDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 23
                }
            }
        ]
    },
    {
        "_id": "e0c47a06-4fe0-46b7-a309-8971bbb3978f",
        "storeName": "VanArsdel, Ltd. | Baby Products Bargains - Elainamouth",
        "top2RecentPromotions": [
            {
                "eventName": "Crazy Deal Days",
                "startDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 21
                }
            }
        ]
    }
]