On this page
cursor.min()
在本页面
Definition
min()方法具有以下参数:
Parameter | Type | Description |
---|---|---|
indexBounds |
document | 索引键的包含性下限。 |
indexBounds
参数具有以下原型形式:
{ field1: <min value>, field2: <min value2>, fieldN:<min valueN> }
这些字段与特定索引的所有键对应(按 Sequences)。您可以使用hint()方法显式指定特定索引。否则,MongoDB 使用indexBounds
中的字段选择索引;但是,如果多个索引存在于具有不同排序 Sequences 的相同字段上,则索引的选择可能会模棱两可。
See also
min()主要用于支持mongos流程,并且是查询修饰符$min的 Shell 包装。
Note
从 v3.2 开始在
mongo
Shell 中弃用从 v3.2 开始,$min运算符在mongo shell 中已弃用。在mongoShell 中,改用cursor.min()。
Behaviors
与索引选择的交互
因为min()需要在字段上构建索引,并强制查询使用该索引,所以如果可能的话,您可能更喜欢使用$gte运算符进行查询。考虑以下示例:
db.products.find( { _id: 7 } ).min( { price: 1.39 } )
该查询将使用price
字段上的索引,即使_id
上的索引可能更好。
Index Bounds
在版本 3.6.6 中进行了更改。
min()没有 max()
min
和max
运算符指示系统应避免常规查询计划。相反,它们构造索引扫描,其中索引范围由min
和max
中给出的值明确指定。
Warning
如果未指定两个边界之一,则查询计划将是一侧无边界的索引扫描。与不包含任何运算符或使用两个运算符来更严格地约束索引扫描的查询相比,这可能会降低性能。
Example
本示例假定一个名为products
的集合包含以下文档:
{ "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }
{ "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }
{ "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }
{ "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
{ "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
{ "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
{ "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }
{ "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
{ "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }
该集合具有以下索引:
{ "_id" : 1 }
{ "item" : 1, "type" : 1 }
{ "item" : 1, "type" : -1 }
{ "price" : 1 }
- 使用
{ item: 1, type: 1 }
索引的 Sequences,min()将查询限制为等于或高于item
等于apple
和type
等于jonagold
的索引键范围的文档,如下所示:
db.products.find().min( { item: 'apple', type: 'jonagold' } ).hint( { item: 1, type: 1 } )
该查询返回以下文档:
{ "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
{ "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
{ "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
{ "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }
{ "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
{ "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }
如果查询没有使用hint()方法显式指定索引,则关于mongod是选择{ item: 1, type: 1 }
索引排序还是{ item: 1, type: -1 }
索引排序是不确定的。
- 使用索引
{ price: 1 }
的 Sequences,min()将查询限制在等于或高于price
等于1.39
的索引键边界的文档,而max()将查询限制到在price
等于1.99
的索引键边界以下的文档:
db.products.find().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )
该查询返回以下文档:
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }