Docs Menu
Docs Home
MongoDB Manual
/ / /


On this page

  • Definition
  • Behavior
  • Examples


Deprecated since v3.2

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

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

mongosh provides the max() wrapper method:

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

You can also specify $max with 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> } } )


Index Use

Starting in MongoDB 4.2, you must explicitly specify the particular index with the hint() method to run max()/ $max with the following exception: you do not need to hint if the find() query is an equality condition on the _id field { _id: <value> }.

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: { $in: [ 6, 7 ] } } ).max( { age: 25 } ).hint( { age: 1 } )

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

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

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

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

    Changed in version 4.0.

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.


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.

The following examples use mongosh wrappers.

Consider the following operations on a collection named collection that has an index { age: 1 }:

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

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.

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


Starting in MongoDB 4.0, the bound specified by $max must be greater than the bound specified by $min.

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