cursor.max()
定义
参数
max() 方法有以下参数
参数 | 类型 | 描述 |
|---|---|---|
indexBounds | 文档 | 索引键的独占上限。 |
indexBounds 参数具有以下原型形式
{ field1: <max value>, field2: <max value2> ... fieldN:<max valueN> }
字段对应于特定索引的所有键的顺序。
兼容性
此方法在以下环境中提供
MongoDB Atlas:云中MongoDB部署的完全托管服务
注意
此命令在所有MongoDB Atlas集群中均受支持。有关所有命令的Atlas支持信息,请参阅不受支持的命令。
MongoDB企业版:基于订阅的自管理MongoDB版本
MongoDB社区版:源代码可用的、免费使用且自管理的MongoDB版本
行为
与索引选择交互
因为 max() 需要在字段上有一个索引,并强制查询使用此索引,如果可能的话,您可能更喜欢使用 $lt 操作符进行查询。考虑以下示例
db.products.find( { _id: { $in: [ 6, 7 ] } } ).max( { price: NumberDecimal("1.39") } ).hint( { price: 1 } )
查询将使用 price 字段的索引,即使 _id 字段的索引可能更好。
索引边界
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 } ] )
使用索引顺序
{ item: 1, type: 1 },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" : 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")或以上的文档。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") }