$max

Definition

  • $max

Deprecated since v3.2

Starting in v3.2, the $max operator is deprecated in themongo shell. In the mongo shell,use cursor.max() instead.

Specify a $max value to specify the exclusive upperbound for a specific index in order to constrain the results offind(). The $max specifies theupper bound for all keys of a specific index in order.

The mongo shell provides the max()wrapper method:

  1. db.collection.find( { <query> } ).max( { field1: <max value>, ... fieldN: <max valueN> } )

You can also specify $max with either of the two forms:

  1. db.collection.find( { <query> } )._addSpecial( "$max", { field1: <max value1>, ... fieldN: <max valueN> } )
  2. db.collection.find( { $query: { <query> }, $max: { field1: <max value1>, ... fieldN: <max valueN> } } )

Behavior

Interaction with Index Selection

Because max() requires an index on a field, andforces the query to use this index, you may prefer the$lt operator for the query if possible. Consider thefollowing example:

  1. db.collection.find( { _id: { $in: [ 6, 7 ] } } ).max( { age: 25 } ).hint( { age: 1 } )

The query uses the index on the age field, even if theindex on _id may be better.

Index Bounds

If you use $max with $min to specify a range:

  • the index bounds specified in $min and $maxmust both refer to the keys of the same index.

  • the bound specified by $max must be greater thanthe bound specified by $min.

Changed in version 4.0.

$max without $min

The min and max operators indicate that the systemshould avoid normal query planning. Instead they construct an index scan wherethe index bounds are explicitly specified by the values given inmin and max.

Warning

If one of the two boundaries is not specified, the query plan will bean index scan that is unbounded on one side. This may degrade performancecompared to a query containing neither operator, or one that uses bothoperators 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 namedcollection that has an index { age: 1 }:

  1. db.collection.find( { <query> } ).max( { age: 100 } ).hint( { age: 1 } )

This operation limits the query to those documents where thefield age is less than 100 and forces a query plan which scans the{ age: 1 } index from MinKeyto 100.

Use with $min

Use $max alone or in conjunction with $min tolimit results to a specific range for the same index, as in thefollowing example:

Note

Changed in version 4.0: The bound specified by $max must be greater than thebound specified by $min.

  1. db.collection.find().min( { age: 20 } ).max( { age: 25 } ).hint( { age: 1 } )