On this page
$max
On this page
Definition
$max-
Note
-
Deprecated in the
mongoShell since v3.2 -
Starting in v3.2, the
$maxoperator is deprecated in themongoshell. In themongoshell, usecursor.max()instead.
Specify a
$maxvalue to specify the exclusive upper bound for a specific index in order to constrain the results offind(). The$maxspecifies the upper bound for all keys of a specific index in order.The
mongoshell provides themax()wrapper method:db.collection.find( { <query> } ).max( { field1: <max value>, ... fieldN: <max valueN> } )You can also specify
$maxwith either of the two forms:db.collection.find( { <query> } )._addSpecial( "$max", { field1: <max value1>, ... fieldN: <max valueN> } ) db.collection.find( { $query: { <query> }, $max: { field1: <max value1>, ... fieldN: <max valueN> } } ) -
Deprecated in the
Behavior
Interaction with Index Selection
Because max() requires an index on a field, and forces the query to use this index, you may prefer the $lt operator for the query if possible. Consider the following example:
db.collection.find( { _id: 7 } ).max( { age: 25 } )
The query uses the index on the age field, even if the index on _id may be better.
$max without $min
The min and max operators indicate that the system should avoid normal query planning. Instead they construct an index scan where the index bounds are explicitly specified by the values given in min and max.
Warning
If one of the two boundaries is not specified, the query plan will be an index scan that is unbounded on one side. This may degrade performance compared to a query containing neither operator, or one that uses both operators to more tightly constrain the index scan.
Examples
The following examples use the mongo shell wrappers.
Specify Exclusive Upper Bound
Consider the following operations on a collection named collection that has an index { age: 1 }:
db.collection.find( { <query> } ).max( { age: 100 } )
This operation limits the query to those documents where the field age is less than 100 and forces a query plan which scans the { age: 1 } index from MinKey to 100.
Index Selection
You can explicitly specify the corresponding index with hint(). Otherwise, MongoDB selects the index using the fields in the $max and $min bounds; however, if multiple indexes exist on same fields with different sort orders, the selection of the index may be ambiguous.
Consider a collection named collection that has the following two indexes:
{ age: 1, type: -1 }
{ age: 1, type: 1 }
Without explicitly using hint(), MongoDB may select either index for the following operation:
db.collection.find().max( { age: 50, type: 'B' } )