$top

$top演算子は、クエリで指定された 1 つ以上のフィールドでドキュメントを並べ替え、フィルター条件に一致する最初のドキュメントを返します。 並べ替えと選択を 1 つの操作で組み合わせることで、個別の並べ替えステージを必要とせずに、最大値または最小値を効率的に検索することができます。

構文

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

パラメーター

パラメーター Description
listOfFields 結果セット内の最後のドキュメントに対して返されるフィールドの一覧
fieldName 結果セットの並べ替えに使用するフィールド
sortOrder 1 または -1。 1 はフィールドの値の昇順で並べ替えを意味し、-1 はフィールドの値の降順で並べ替えを意味します

例示

stores コレクションのこのサンプル ドキュメントについて考えてみましょう。

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

このクエリによって返される最初の 2 つの結果は次のとおりです。

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