$lastN

$lastN アキュムレータ演算子は、指定された式のドキュメントのグループ内の最後の N 個の値を返します。 これは、並べ替えられたコレクションから、最後の 1 つの値だけでなく、複数の末尾の値を取得する必要がある場合に便利です。

構文

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

パラメーター

パラメーター Description
n 返される値の数。 正の整数にする必要があります。
input 最後に出現する N 個のフィールドまたは値を指定する式。

例示

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: アキュムレータとして $lastN を使用して、ストアごとに最後の 2 つのプロモーション イベントを検索する

各ストアの最後の 2 つのプロモーション イベントを取得するには、クエリを実行して、プロモーション イベントを開始日の昇順で並べ替え、並べ替えられたイベントをストア別にグループ化し、各ストア内の最後の 2 つのイベントを返します。

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
                }
            }
        }
    }
])

このクエリによって返される最初の 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をアキュムレータとして使用して、売上の 3 つの最も高い販売カテゴリを見つける

店舗あたりの売り上げが最も高い販売カテゴリを取得するには、クエリを実行して販売カテゴリを販売量の昇順で並べ替え、並べ替えられた結果を店舗別にグループ化し、店舗ごとに最後の 3 つのカテゴリを返します。

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
                }
            }
        }
    }
])

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

[
    {
        "_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 演算子を使用して、最後の 2 つの昇格イベントを取得する

この例では、店舗から最後または最新の 2 つのプロモーション イベントを検索するためのオペレーターの使用状況を示します。

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