$min¶
Definition¶
$min
¶- NoteDeprecated since v3.2
Starting in v3.2, the
$min
operator is deprecated in themongo
shell. In themongo
shell, usecursor.min()
instead.Specify a
$min
value to specify the inclusive lower bound for a specific index in order to constrain the results offind()
. The$min
specifies the lower bound for all keys of a specific index in order.The
mongo
shell provides themin()
wrapper method:db.collection.find( { <query> } ).min( { field1: <min value>, ... fieldN: <min valueN>} ) You can also specify the option with either of the two forms:
db.collection.find( { <query> } )._addSpecial( "$min", { field1: <min value1>, ... fieldN: <min valueN> } ) db.collection.find( { $query: { <query> }, $min: { field1: <min value1>, ... fieldN: <min valueN> } } )
Behavior¶
Interaction with Index Selection¶
Because min()
requires an index on a field, and
forces the query to use this index, you may prefer the
$gte
operator for the query if possible. Consider the
following example:
db.collection.find( { _id: { $in: [ 6, 7 ] } } ).min( { age: 25 } ).hint( { age: 1 } )
The query will use the index on the age
field, even if the
index on _id
may be better.
Index Bounds¶
$min
without $max
¶
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.
Examples¶
The following examples use the mongo
shell wrappers.
Specify Inclusive Lower Bound¶
Consider the following operations on a collection named
collection
that has an index { age: 1 }
:
db.collection.find().min( { age: 20 } ).hint( { age: 1 } )
This operation limits the query to those documents where the
field age
is at least 20
and forces a query plan which scans the
{ age: 1 }
index from 20 to MaxKey.
Use with $max
¶
You can use $min
in conjunction with $max
to
limit results to a specific range for the same index, as in the
following example:
db.collection.find().min( { age: 20 } ).max( { age: 25 } ).hint( { age: 1 } )