$maxN

運算子 $maxN 是用來根據指定的篩選準則擷取字段的前 N 個值。

語法

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

參數

參數 Description
input 指定要評估最大值的欄位或表示式。
n 指定要擷取的最大值數目。 必須是正整數。

範例

請參考商店集合中的此範例檔。

{
  "_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:使用 $maxN as accumulator 來擷取前兩個銷售類別

此查詢會擷取具有高效能類別的前兩個銷售類別,或彙總商店中的熱門類別。

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 個折扣。 此查詢會篩選 2023 年的「筆記型電腦」折扣條目,然後按城市將產生的文件分組。

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

此查詢傳回的前三個結果為:

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

範例 3:使用 $maxN 運算符作為 array-expression 來尋找前三個銷售類別

此查詢會從所有銷售類別擷取前三個銷售值。

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