Definition
Changed in version 5.0.
$max
Returns the maximum value. $max compares both value and type, using the specified BSON comparison order for values of different types.
$max is available in these stages:
$addFields$bucket$bucketAuto$group$matchstage that includes an$exprexpression$project$replaceRoot$replaceWith$set$setWindowFields(Available starting in MongoDB 5.0)
Syntax
When used in the $bucket, $bucketAuto, $group, and $setWindowFields stages, $max has this syntax:
{ $max: <expression> }When used in other supported stages, $max has one of two syntaxes:
$maxhas one specified expression as its operand:{ $max: <expression> }$maxhas a list of specified expressions as its operand:{ $max: [ <expression1>, <expression2> ... ] }For more information on expressions, see Expressions.
Behavior
Result Type
$maxcompares input data following the BSON Comparison order to determine the appropriate output type. When the input data contains multiple data types, the$maxoutput type is the highest in the comparison order.Null or Missing Values
If some, but not all, documents for the
$maxoperation have either anullvalue for the field or are missing the field, the$maxoperator only considers the non-null and the non-missing values for the field.If all documents for the
$maxoperation havenullvalue for the field or are missing the field, the$maxoperator returnsnullfor the maximum value.Array Operand
In the
$groupand$setWindowFieldsstages, if the expression resolves to an array,$maxdoes not traverse the array and compares the array as a whole.In the other supported stages:
- With a single expression as its operand, if the expression resolves to an array,
$maxtraverses into the array to operate on the numeric elements of the array to return a single value. - With a list of expressions as its operand, if any of the expressions resolves to an array,
$maxdoes not traverse into the array but instead treats the array as a non-numeric value.
Examples
Use in
$groupStageConsider a
salescollection with the following documents:db.sales.insertMany ( [
{ _id : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") },
{ _id : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") },
{ _id : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") },
{ _id : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") },
{ _id : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }
] )Grouping the documents by the
itemfield, the following operation uses the$maxaccumulator to compute the maximum total amount and maximum quantity for each group of documents.db.sales.aggregate(
[
{
$group:
{
_id: "$item",
maxTotalAmount: { $max: { $multiply: [ "$price", "$quantity" ] } },
maxQuantity: { $max: "$quantity" }
}
}
]
)The operation returns the following results:
{ "_id" : "xyz", "maxTotalAmount" : 50, "maxQuantity" : 10 }
{ "_id" : "jkl", "maxTotalAmount" : 20, "maxQuantity" : 1 }
{ "_id" : "abc", "maxTotalAmount" : 100, "maxQuantity" : 10 }Use in
$projectStageA collection
studentscontains the following documents:db.students.insertMany( [
{ _id: 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 },
{ _id: 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 },
{ _id: 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 }
] )The following example uses the
$maxin the$projectstage to calculate the maximum quiz scores, the maximum lab scores, and the maximum of the final and the midterm:db.students.aggregate([
{ $project: { quizMax: { $max: "$quizzes"}, labMax: { $max: "$labs" }, examMax: { $max: [ "$final", "$midterm" ] } } }
])The operation results in the following documents:
{ "_id" : 1, "quizMax" : 10, "labMax" : 8, "examMax" : 80 }
{ "_id" : 2, "quizMax" : 10, "labMax" : 8, "examMax" : 95 }
{ "_id" : 3, "quizMax" : 5, "labMax" : 6, "examMax" : 78 }Use in
$setWindowFieldsStageNew in version 5.0.
Create a
cakeSalescollection that contains cake sales in the states of California (CA) and Washington (WA):db.cakeSales.insertMany( [
{ _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
state: "CA", price: 13, quantity: 120 },
{ _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
state: "WA", price: 14, quantity: 140 },
{ _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
state: "CA", price: 12, quantity: 145 },
{ _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
state: "WA", price: 13, quantity: 104 },
{ _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
state: "CA", price: 41, quantity: 162 },
{ _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
state: "WA", price: 43, quantity: 134 }
] )This example uses
$maxin the$setWindowFieldsstage to output the maximumquantityof cake sales for eachstate:db.cakeSales.aggregate( [
{
$setWindowFields: {
partitionBy: "$state",
sortBy: { orderDate: 1 },
output: {
maximumQuantityForState: {
$max: "$quantity",
window: {
documents: [ "unbounded", "current" ]
}
}
}
}
}
] )In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.
outputsets themaximumQuantityForStatefield to the maximumquantityvalue using$maxthat is run in a documents window.The window contains documents between an
unboundedlower limit and thecurrentdocument in the output. This means$maxreturns the maximumquantityfor the documents between the beginning of the partition and the current document.
In this output, the maximum
quantityforCAandWAis shown in themaximumQuantityForStatefield:{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),
"state" : "CA", "price" : 41, "quantity" : 162, "maximumQuantityForState" : 162 }
{ "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),
"state" : "CA", "price" : 13, "quantity" : 120, "maximumQuantityForState" : 162 }
{ "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),
"state" : "CA", "price" : 12, "quantity" : 145, "maximumQuantityForState" : 162 }
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),
"state" : "WA", "price" : 43, "quantity" : 134, "maximumQuantityForState" : 134 }
{ "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),
"state" : "WA", "price" : 13, "quantity" : 104, "maximumQuantityForState" : 134 }
{ "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),
"state" : "WA", "price" : 14, "quantity" : 140, "maximumQuantityForState" : 140 }