Docs 主页 → 开发应用程序 → MongoDB Manual
cursor.max()
定义
cursor.max()
重要
mongosh 方法
本页介绍了
mongosh
方法。这不是特定于语言的驱动程序(例如 Node.js)的文档。对于 MongoDB API 驱动程序,请参阅特定语言的MongoDB 驱动程序文档。
参数
max()
方法具有以下参数:
范围 | 类型 | 说明 |
---|---|---|
indexBounds | 文档 | 索引键的独占上限。 |
indexBounds
参数具有以下原型形式:
{ field1: <max value>, field2: <max value2> ... fieldN:<max valueN> }
这些字段按顺序对应于特定索引的所有键。
提示
另请参阅:
行为
与索引选择的交互
由于max()
需要字段上的索引,并强制查询使用此索引,因此如果可能,您可能更愿意使用$lt
操作符进行查询。考虑以下示例:
db.products.find( { _id: { $in: [ 6, 7 ] } } ).max( { price: NumberDecimal("1.39") } ).hint( { price: 1 } )
查询将使用price
字段上的索引,即使_id
上的索引可能更好。
索引边界
max()
指定的边界必须大于min()
指定的边界。
max()
無 min()
min()
和max()
方法指示系统应避免正常的查询计划。它们构造索引扫描,其中索引边界由min()
和max()
中给出的值显式指定。
警告
如果未指定两个边界之一,则查询计划将是在一侧无边界的索引扫描。与不含操作符的查询或使用两个操作符来更严格地限制索引扫描的查询相比,这可能会降低性能。
例子
注意
对于以下示例,创建一个名为products
的样本集合,其中包含以下文档:
db.products.insertMany([ { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : NumberDecimal("1.99") }, { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : NumberDecimal("1.99") }, { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : NumberDecimal("1.29") }, { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : NumberDecimal("1.29") }, { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : NumberDecimal("1.29") }, { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : NumberDecimal("1.29") }, { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : NumberDecimal("2.99") }, { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : NumberDecimal("1.99") }, { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : NumberDecimal("0.99") }, { "_id" : 10, "item" : "orange", "type" : "navel", "price" : NumberDecimal("1.39") } ])
为集合创建以下索引:
db.products.createIndexes( [ { "item" : 1, "type" : 1 }, { "item" : 1, "type" : -1 }, { "price" : 1 } ] )
max()
使用{ item: 1, type: 1 }
索引的排序,将查询限制为低于item
等于apple
且type
等于jonagold
边界的文档:db.products.find().max( { item: 'apple', type: 'jonagold' } ).hint( { item: 1, type: 1 } ) 该查询返回以下文档:
{ "_id" : 6, "item" : "apple", "type" : "cortland", "price" : NumberDecimal("1.29") } { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : NumberDecimal("1.99") } { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : NumberDecimal("1.99") } 使用索引
{ price: 1 }
的顺序,max()
将查询限制为低于price
索引键边界等于NumberDecimal("1.99")
的文档,而min()
将查询限制为等于或高于price
的索引键边界等于NumberDecimal("1.39")
:注意
max()
指定的边界必须大于min()
指定的边界。db.products.find().min( { price: NumberDecimal("1.39") } ).max( { price: NumberDecimal("1.99") } ).hint( { price: 1 } ) 该查询返回以下文档:
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : NumberDecimal("1.39") }