$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 - 총 판매액이 가장 낮은 두 매장 가져오기

First Up Consultants 회사 내에서 판매 기준으로 가장 낮은 두 개의 매장을 얻으려면 쿼리를 실행하여 회사 이름을 필터링하고 결과 문서를 오름차순으로 정렬하고 정렬된 결과 집합에서 상위 2개의 문서를 반환합니다.

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: 가장 최근의 두 가지 승격 이벤트 가져오기

각 저장소에 대한 가장 최근의 두 가지 프로모션 이벤트를 찾으려면 컬렉션의 문서를 저장소별로 그룹화하고, 승격 날짜의 오름차순으로 정렬하고, 저장소당 정렬된 결과 집합에서 상위 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
                }
            }
        ]
    }
]