$maxN

运算符 $maxN 用于根据指定的筛选条件检索字段的前 N 个值。

语法

$maxN: {
    input: < field or expression > ,
    n: < number of values to retrieve >
}

参数

参数 DESCRIPTION
input 指定要计算最大值的字段或表达式。
n 指定要检索的最大值的数目。 必须是正整数。

例子

让我们了解 stores 数据集中的示例 json 的用法。

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
  "location": {
    "lat": 60.1441,
    "lon": -141.5012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 2,
      "partTime": 0
    }
  },
  "sales": {
    "salesByCategory": [
      {
        "categoryName": "DJ Headphones",
        "totalSales": 35921
      }
    ],
    "fullSales": 3700
  },
  "promotionEvents": [
    {
      "eventName": "Bargain Blitz Days",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 3,
          "Day": 11
        },
        "endDate": {
          "Year": 2024,
          "Month": 2,
          "Day": 18
        }
      },
      "discounts": [
        {
          "categoryName": "DJ Turntables",
          "discountPercentage": 18
        },
        {
          "categoryName": "DJ Mixers",
          "discountPercentage": 15
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ],
  "company": "Lakeshore Retail",
  "city": "Port Cecile",
  "lastUpdated": {
    "$date": "2024-12-11T10:21:58.274Z"
  }
}

示例 1:用于$maxNaccumulator检索前两个销售类别

该查询检索具有高性能类别的前两个销售类别,或跨商店聚合顶级类别。

db.stores.aggregate([{
        $project: {
            topSalesCategories: {
                $maxN: {
                    input: "$sales.salesByCategory",
                    n: 2
                }
            }
        }
    },
    {
        $limit: 4
    }
])

此查询返回以下结果:

[
  {
    "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
    "topSalesCategories": [
      {
        "categoryName": "Stockings",
        "totalSales": 25731
      }
    ]
  },
  {
    "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5",
    "topSalesCategories": [
      {
        "categoryName": "Markers",
        "totalSales": 3927
      }
    ]
  },
  {
    "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312",
    "topSalesCategories": [
      {
        "categoryName": "Storage Boxes",
        "totalSales": 2236
      }
    ]
  },
  {
    "_id": "94792a4c-4b03-466b-91f6-821c4a8b2aa4",
    "topSalesCategories": [
      {
        "categoryName": "Travel Backpacks",
        "totalSales": 13189
      },
      {
        "categoryName": "Suitcases",
        "totalSales": 37858
      }
    ]
  }
]

示例 2:使用$maxN$setWindowFields

该示例有助于检索每个城市 2023 年“笔记本电脑”的最高 N 折扣。

db.stores.aggregate([
  { $unwind: "$promotionEvents" },
  { $unwind: "$promotionEvents.discounts" },
  {
    $match: {
      "promotionEvents.discounts.categoryName": "Laptops",
      "promotionEvents.promotionalDates.startDate.Year": 2023
    }
  },
  {
    $group: {
      _id: "$city",
      allDiscounts: {
        $push: "$promotionEvents.discounts.discountPercentage"
      }
    }
  },
  {
    $project: {
      topDiscounts: {
        $slice: [
          { $sortArray: { input: "$allDiscounts", sortBy: -1 } },
          3 // Top N discounts
        ]
      }
    }
  }
])

查询筛选“笔记本电脑”折扣条目,其 startDate.Year 为 2023 年,然后按城市对它们进行分组。 它收集并排序所有折扣百分比,并返回每个城市的前 3 个折扣。 输出限制为响应返回 3 个城市。

[
    {
        "_id": "Lake Margareteland",
        "topDiscounts": [
            18
        ]
    },
    {
        "_id": "Horacetown",
        "topDiscounts": [
            13
        ]
    },
    {
        "_id": "D'Amoreside",
        "topDiscounts": [
            9
        ]
    }
]

示例 3:使用 $maxN 运算符作为数组表达式查找前三个销售类别

该示例演示如何使用运算符查找所有销售类别的前三个销售值。

db.stores.aggregate([
  { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} },
  {
    $project: {
      name: 1,
      topThreeSales: {
        $maxN: {
          input: "$sales.salesByCategory.totalSales",
          n: 3
        }
      }
    }
  }
])

该查询返回提供的文档的前三个销售值。

{
  "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
  "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
  "topThreeSales": [43522, 32272, 28946]
}