$lastN

$lastN 累加器运算符返回一组文档中指定表达式的最后 N 个值。 需要从排序的集合中检索多个最终值而不仅仅是最后那个值时,它很有用。

Syntax

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