$top

運算子 $top 會在查詢指定的一或多個字段上排序檔,並傳回符合篩選準則的第一份檔。 此運算子會在單一作業中結合排序和選取,使其有效率地尋找最高或最低的值,而不需要個別的排序階段。

語法

{
    $top: {
      output: [listOfFields],
      sortBy: {
          < fieldName >: < sortOrder >
      }
  }
}

參數

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

範例

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

{
    "_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:取得每個商店的熱門銷售類別

若要在 First Up Consultants 公司內尋找最高銷售類別,請執行查詢以擷取公司內的商店、依每個類別內總銷售額遞減順序排序檔,並傳回排序結果集中的最上層檔。

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

此查詢會傳回下列結果:

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

範例 2:依促銷類別取得最高折扣

若要擷取每個銷售類別的最高折扣,請先執行查詢以依市集分組所有檔,然後依每個促銷事件中的折扣百分比遞減順序排序檔,然後從每個商店的已排序結果集傳回最上層檔。

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $unwind: "$promotionEvents.discounts"
    },
    {
        $group: {
            _id: "$_id",
            storeName: {
                $first: "$name"
            },
            highestDiscount: {
                $top: {
                    sortBy: {
                        "promotionEvents.discounts.discountPercentage": -1
                    },
                    output: {
                        categoryName: "$promotionEvents.discounts.categoryName",
                        discountPercentage: "$promotionEvents.discounts.discountPercentage",
                        eventName: "$promotionEvents.eventName"
                    }
                }
            }
        }
    }
])

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

[
    {
        "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1",
        "storeName": "First Up Consultants | Computer Gallery - West Cathrine",
        "highestDiscount": {
            "categoryName": "Gaming Accessories",
            "discountPercentage": 24,
            "eventName": "Crazy Markdown Madness"
        }
    },
    {
        "_id": "a58d0356-493b-44e6-afab-260aa3296930",
        "storeName": "Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie",
        "highestDiscount": {
            "categoryName": "Fire Pits",
            "discountPercentage": 22,
            "eventName": "Savings Showdown"
        }
    }
]