- Reference >
- JavaScript Methods >
- cursor.max()
cursor.max()¶
-
cursor.
max
()¶ The
max()
method specifies the exclusive upper bound for a specific index in order to constrain the results offind()
.max()
provides a way to specify an upper bound on compound key indexes.max()
takes the following parameter:Parameters: - indexBounds (document) –
Specifies the exclusive upper bound for the index keys. The
indexBounds
parameter has the following prototype form:The fields correspond to all the keys of a particular index in order. You can explicitly specify the particular index with the
hint()
method. Otherwise,mongod
selects the index using the fields in theindexBounds
; however, if multiple indexes exist on same fields with different sort orders, the selection of the index may be ambiguous.
See also
Consider the following example of
max()
, which assumes a collection namedproducts
that holds the following documents:The collection has the following indexes:
Using the ordering of
{ item: 1, type: 1 }
index,max()
limits the query to the documents that are below the bound ofitem
equal toapple
andtype
equal tojonagold
:The query returns the following documents:
If the query did not explicitly specify the index with the
hint()
method, it is ambiguous as to whethermongod
would select the{ item: 1, type: 1 }
index ordering or the{ item: 1, type: -1 }
index ordering.Using the ordering of the index
{ price: 1 }
,max()
limits the query to the documents that are below the index key bound ofprice
equal to1.99
andmin()
limits the query to the documents that are at or above the index key bound ofprice
equal to1.39
:The query returns the following documents:
Note
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:The query will use the index on the
price
field, even if the index on_id
may be better.max()
exists primarily to support themongos
(sharding) process.If you use
max()
withmin()
to specify a range, the index bounds specified inmin()
andmax()
must both refer to the keys of the same index.
- indexBounds (document) –