On this page
cursor.max()
在本页面
Definition
max()方法具有以下参数:
Parameter | Type | Description |
---|---|---|
indexBounds |
document | 索引键的排他上限。 |
indexBounds
参数具有以下原型形式:
{ field1: <max value>, field2: <max value2> ... fieldN:<max valueN> }
这些字段与特定索引的所有键对应(按 Sequences)。您可以使用hint()方法显式指定特定索引。否则,mongod使用indexBounds
中的字段选择索引;但是,如果多个索引存在于具有不同排序 Sequences 的相同字段上,则索引的选择可能会模棱两可。
See also
max()主要用于支持mongos(分片)过程,并且是查询修饰符$max的 Shell 包装。
Note
从 v3.2 开始在
mongo
Shell 中弃用从 v3.2 开始,$max运算符在mongo shell 中已弃用。在mongoShell 中,改用cursor.max()。
Behavior
与索引选择的交互
因为max()需要在字段上构建索引,并强制查询使用该索引,所以如果可能的话,您可能更喜欢使用$lt运算符进行查询。考虑以下示例:
db.products.find( { _id: 7 } ).max( { price: 1.39 } )
该查询将使用price
字段上的索引,即使_id
上的索引可能更好。
Index Bounds
在版本 3.6.6 中进行了更改。
max()没有 min()
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,max()将查询限制到item
等于apple
和type
等于jonagold
的边界以下的文档:
db.products.find().max( { item: 'apple', type: 'jonagold' } ).hint( { item: 1, type: 1 } )
该查询返回以下文档:
{ "_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 }
如果查询没有使用hint()方法显式指定索引,则关于mongod是选择{ item: 1, type: 1 }
索引排序还是{ item: 1, type: -1 }
索引排序是不确定的。
db.products.find().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )
该查询返回以下文档:
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }