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