$max

$max運算子會傳回一組輸入值的最大值。

當用作欄位更新運算子時, $max 如果指定的值大於欄位的現行值,則運算子會將欄位的值更新為指定的值。 如果欄位不存在, $max 請建立 欄位,並將它設定為指定的值。

語法

$max: <expression>

當用作欄位更新運算子時:

{
  $max: {
    <field1>: <value1>,
    <field2>: <value2>,
    ...
  }
}

參數

參數 Description
<expression> 任何解析為值的有效表達式。 運算子 $max 會評估此運算式,以判斷最大值。

當用作欄位更新運算子時:

參數 Description
field 要以最大值更新的功能變數名稱。
value 要與目前域值比較的值。 只有在此值較大時,才會更新欄位。

範例

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

{
    "_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:依類別計算最高銷售額

若要計算每個類別內的最高銷售額,請先執行查詢,依銷售類別將所有文件分組。 然後執行$max查詢,以擷取所有商店中每個類別內的最高銷售額。

db.stores.aggregate([{
        $unwind: "$sales.salesByCategory"
    },
    {
        $group: {
            _id: "$sales.salesByCategory.categoryName",
            maxSales: {
                $max: "$sales.salesByCategory.totalSales"
            }
        }
    }
])

此查詢傳回的前五個結果如下:

[
    {
        "_id": "Christmas Trees",
        "maxSales": 49697
    },
    {
        "_id": "Nuts",
        "maxSales": 48020
    },
    {
        "_id": "Camping Tables",
        "maxSales": 48568
    },
    {
        "_id": "Music Theory Books",
        "maxSales": 46133
    },
    {
        "_id": "Fortified Wine",
        "maxSales": 49912
    }
]

範例 2:在 中使用$max$bucket

若要擷取銷售邊界值內的最高銷售額:

db.stores.aggregate([{
    $bucket: {
        groupBy: "$sales.totalSales",
        boundaries: [0, 1000, 5000, 10000],
        default: "Other",
        output: {
            maxSales: {
                $max: "$sales.totalSales"
            }
        }
    }
}])

此查詢會傳回下列結果:

[
    {
        "_id": 1000,
        "maxSales": 4996
    },
    {
        "_id": "Other",
        "maxSales": 404106
    },
    {
        "_id": 0,
        "maxSales": 995
    },
    {
        "_id": 5000,
        "maxSales": 9999
    }
]

範例 3:在 中使用$max$setWindowFields

要在 2023 年獲得筆記本電腦的最高折扣,請先運行查詢以僅展開促銷活動並過濾所選類別。 然後按公司對生成的文件進行分區,並計算每個生成分區中的最高折扣百分比。

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $unwind: "$promotionEvents.discounts"
    },
    // Filter only Laptops category and events in 2023
    {
        $match: {
            "promotionEvents.promotionalDates.startDate.Year": 2023,
            "promotionEvents.discounts.categoryName": "Laptops"
        }
    },
    // Use $setWindowFields to calculate average discount by city
    {
        $setWindowFields: {
            partitionBy: "$company",
            output: {
                maxDiscount: {
                    $max: "$promotionEvents.discounts.discountPercentage",
                    window: {
                        documents: ["unbounded", "unbounded"]
                    }
                }
            }
        }
    },
    // Group by city to return one result per city
    {
        $group: {
            _id: "$company",
            maxDiscount: {
                $first: "$maxDiscount"
            }
        }
    }
])

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

[
    {
        "_id": "Proseware, Inc.",
        "maxDiscount": 24
    },
    {
        "_id": "Fabrikam, Inc.",
        "maxDiscount": 23
    },
    {
        "_id": "Contoso, Ltd.",
        "maxDiscount": 24
    }
]

範例 4:設定最大員工容量 (欄位更新操作員)

若要僅在目前全職員工計數較低時將全職員工更新為 10,請使用欄位上的$max運算子來執行更新。 由於目前的 fullTime 值為 3,且 10 大於 3,因此字段會更新為 10。

db.stores.updateOne(
  { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" },
  {
    $max: {
      "staff.totalStaff.fullTime": 10
    }
  }
)

範例 5:多個欄位更新 (欄位更新運算子)

若要使用最大值更新多個欄位,請使用具有多個欄位及其對應的最大值的$max運算子來設定。

db.stores.updateOne(
  { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" },
  {
    $max: {
      "staff.totalStaff.partTime": 1,
      "sales.totalSales": 50000
    }
  }
)

在此案例中:

  • partTime (2) 自 1 < 2 日起維持 2 (無變更)
  • totalSales(31211) 自 50000 31211 年以來將更新為 50000 >

範例 6:建立新欄位 (欄位更新運算子)

如果欄位不存在, $max 請使用指定的值加以建立。

db.stores.updateOne(
  { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" },
  {
    $max: {
      "staff.maxStaffCapacity": 25,
      "sales.peakSalesRecord": 100000
    }
  }
)

範例 7:更新陣列元素 (欄位更新運算子)

使用位置運算子更新陣列元素內的最大值。

db.stores.updateOne(
  {
    _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66",
    "sales.salesByCategory.categoryName": "Phone Mounts"
  },
  {
    $max: {
      "sales.salesByCategory.$.totalSales": 12000
    }
  }
)

範例 8:追蹤尖峰效能 (欄位更新運算子)

設定只有在超過時才會更新的尖峰效能計量。

db.stores.updateOne(
  { _id: "f2a8c190-28e4-4e14-9d8b-0256e53dca66" },
  {
    $max: {
      "performance.peakDailySales": 5000,
      "performance.maxCustomersPerDay": 150,
      "performance.highestSalesMonth": 45000
    }
  }
)

在這些欄位更新作業之後,更新的文件為:

{
  "_id": "f2a8c190-28e4-4e14-9d8b-0256e53dca66",
  "name": "Fabrikam, Inc. | Car Accessory Outlet - West Adele",
  "staff": {
    "totalStaff": {
      "fullTime": 10,
      "partTime": 2
    },
    "maxStaffCapacity": 25
  },
  "sales": {
    "totalSales": 50000,
    "peakSalesRecord": 100000,
    "salesByCategory": [
      {
        "categoryName": "Phone Mounts",
        "totalSales": 12000
      },
      {
        "categoryName": "Dash Cameras",
        "totalSales": 22300
      }
    ]
  },
  "performance": {
    "peakDailySales": 5000,
    "maxCustomersPerDay": 150,
    "highestSalesMonth": 45000
  },
  "lastPromotionDate": ISODate("2024-12-31T00:00:00.000Z"),
  "inventoryDeadline": ISODate("2024-06-30T00:00:00.000Z")
}