$lastN

$lastN 누적기 연산자는 지정된 식에 대한 문서 그룹의 마지막 N개 값을 반환합니다. 정렬된 컬렉션에서 마지막 값 하나만 검색하는 것이 아니라 여러 개의 최종 값을 검색해야 할 때 유용합니다.

문법

{
    $group: {
        _id: < expression > ,
        < field >: {
            $lastN: {
                 n: < number >,
                 input: < expression >               
            }
        }
    }
}

매개 변수

매개 변수 Description
n 반환할 값의 개수. 양의 정수여야 합니다.
input 마지막 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: $lastN 누적기로 사용하여 스토어에서 마지막 두 가지 프로모션 이벤트 찾기

각 저장소에 대한 마지막 두 개의 승격 이벤트를 검색하려면 쿼리를 실행하여 시작 날짜의 오름차순으로 승격 이벤트를 정렬하고, 정렬된 이벤트를 저장소별로 그룹화하고, 각 저장소 내의 마지막 두 이벤트를 반환합니다.

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $sort: {
            "promotionEvents.promotionalDates.startDate.Year": 1,
            "promotionEvents.promotionalDates.startDate.Month": 1,
            "promotionEvents.promotionalDates.startDate.Day": 1
        }
    },
    {
        $group: {
            _id: "$_id",
            storeName: {
                $last: "$name"
            },
            lastTwoPromotions: {
                $lastN: {
                    input: "$promotionEvents.eventName",
                    n: 2
                }
            },
            lastTwoPromotionDates: {
                $lastN: {
                    input: "$promotionEvents.promotionalDates.startDate",
                    n: 2
                }
            }
        }
    }
])

이 쿼리에서 반환된 처음 두 가지 결과는 다음과 같습니다.

[
    {
        "_id": "e28fff9b-a8fb-4ac9-bb37-dea60d2a7d32",
        "storeName": "Lakeshore Retail | Outdoor Furniture Collection - Erdmanside",
        "lastTwoPromotions": [
            "Big Bargain Bash",
            "Spectacular Savings Showcase"
        ],
        "lastTwoPromotionDates": [
            {
                "Year": 2024,
                "Month": 9,
                "Day": 21
            },
            {
                "Year": 2024,
                "Month": 6,
                "Day": 23
            }
        ]
    },
    {
        "_id": "1bec7539-dc75-4f7e-b4e8-afdf8ff2f234",
        "storeName": "Adatum Corporation | Health Food Market - East Karina",
        "lastTwoPromotions": [
            "Price Slash Spectacular",
            "Spectacular Savings Showcase"
        ],
        "lastTwoPromotionDates": [
            {
                "Year": 2024,
                "Month": 9,
                "Day": 21
            },
            {
                "Year": 2024,
                "Month": 6,
                "Day": 23
            }
        ]
    }
]

예제 2: $lastN 누적기로 사용하여 세 가지 가장 높은 판매 범주를 찾습니다.

매장당 가장 많이 판매된 판매 범주를 검색하려면 쿼리를 실행하여 판매 범주를 오름차순으로 정렬하고, 정렬된 결과를 매장별로 그룹화하고, 매장당 마지막 세 가지 범주를 반환합니다.

db.stores.aggregate([{
        $unwind: "$sales.salesByCategory"
    },
    {
        $sort: {
            "sales.salesByCategory.totalSales": 1
        }
    },
    {
        $group: {
            _id: "$_id",
            storeName: {
                $last: "$name"
            },
            top3Categories: {
                $lastN: {
                    input: "$sales.salesByCategory.categoryName",
                    n: 3
                }
            },
            top3SalesAmounts: {
                $lastN: {
                    input: "$sales.salesByCategory.totalSales",
                    n: 3
                }
            }
        }
    }
])

이 쿼리에서 반환된 처음 두 가지 결과는 다음과 같습니다.

[
    {
        "_id": "22e6367e-8341-415f-9795-118d2b522abf",
        "storeName": "Adatum Corporation | Outdoor Furniture Mart - Port Simone",
        "top3Categories": [
            "Outdoor Benches"
        ],
        "top3SalesAmounts": [
            4976
        ]
    },
    {
        "_id": "a00a3ccd-49a2-4e43-b0d9-e56b96113ed0",
        "storeName": "Wide World Importers | Smart Home Deals - Marcuschester",
        "top3Categories": [
            "Smart Thermostats",
            "Smart Plugs"
        ],
        "top3SalesAmounts": [
            38696,
            633
        ]
    }
]

예제 3: $lastN 연산을 배열 식으로 사용하여 마지막 두 개의 승격 이벤트를 가져옵니다.

이 예제에서는 저장소에서 마지막 또는 가장 최근 두 개의 승격 이벤트를 찾기 위한 연산자 사용을 보여 줍니다.

db.stores.aggregate([
  { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} },
  {
    $project: {
      name: 1,
      lastTwoPromotions: {
        $lastN: {
          input: "$promotionEvents",
          n: 2
        }
      }
    }
  }
])

이 쿼리는 다음 결과를 반환합니다.

[
  {
      "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
      "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
      "lastTwoPromotions": [
          {
              "eventName": "Grand Deal Days",
              "promotionalDates": {
                  "startDate": {
                      "Year": 2024,
                      "Month": 6,
                      "Day": 23
                  },
                  "endDate": {
                      "Year": 2024,
                      "Month": 6,
                      "Day": 30
                  }
              },
              "discounts": [
                  {
                      "categoryName": "Remote Controls",
                      "discountPercentage": 7
                  },
                  {
                      "categoryName": "Televisions",
                      "discountPercentage": 11
                  },
                  {
                      "categoryName": "Business Projectors",
                      "discountPercentage": 13
                  },
                  {
                      "categoryName": "Laser Projectors",
                      "discountPercentage": 6
                  },
                  {
                      "categoryName": "Projectors",
                      "discountPercentage": 6
                  },
                  {
                      "categoryName": "Projector Screens",
                      "discountPercentage": 24
                  }
              ]
          },
          {
              "eventName": "Major Bargain Bash",
              "promotionalDates": {
                  "startDate": {
                      "Year": 2024,
                      "Month": 9,
                      "Day": 21
                  },
                  "endDate": {
                      "Year": 2024,
                      "Month": 9,
                      "Day": 30
                  }
              },
              "discounts": [
                  {
                      "categoryName": "Sound Bars",
                      "discountPercentage": 9
                  },
                  {
                      "categoryName": "VR Games",
                      "discountPercentage": 7
                  },
                  {
                      "categoryName": "Xbox Games",
                      "discountPercentage": 25
                  },
                  {
                      "categoryName": "Projector Accessories",
                      "discountPercentage": 18
                  },
                  {
                      "categoryName": "Mobile Games",
                      "discountPercentage": 8
                  },
                  {
                      "categoryName": "Projector Cases",
                      "discountPercentage": 22
                  }
              ]
          }
      ]
  }
]