光标.min()
定义
兼容性
此方法在以下环境中部署时可用
MongoDB Atlas:云中 MongoDB 部署的完全托管服务
注意
此命令在所有 MongoDB Atlas 集群中受支持。有关 Atlas 对所有命令的支持信息,请参阅 不受支持的命令。
MongoDB Enterprise:基于订阅的自托管 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自托管 MongoDB 版本
行为
与索引选择交互
因为 min() 需要一个字段上的索引,并强制查询使用此索引,如果可能的话,您可能更喜欢查询中使用 $gte 操作符。考虑以下示例
db.products.find( { $in: [ 6, 7 ] } ).min( { price: NumberDecimal("1.39") } ).hint( { price: 1 })
查询将使用 price 字段的索引,即使 _id 的索引可能更好。
索引边界
没有 max() 的 min()
min() 和 max() 方法表示系统应避免正常查询规划。它们构建了一个索引扫描,其中索引边界由 min() 和 max() 中给出的值显式指定。
警告
如果两个边界中未指定其中一个,查询计划将是一个在一边无界的索引扫描。这可能与没有这两个操作符或同时使用这两个操作符来更严格约束索引扫描的查询相比降低性能。
示例
除非 find() 查询是针对 _id 字段的等值条件 { _id: <value> },否则您必须使用 hint() 方法显式指定索引以运行 min()。
以下示例中,创建一个名为 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 }索引的顺序,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" : NumberDecimal("1.29") } { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : NumberDecimal("1.29") } { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : NumberDecimal("1.29") } { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : NumberDecimal("2.99") } { "_id" : 10, "item" : "orange", "type" : "navel", "price" : NumberDecimal("1.39") } { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : NumberDecimal("1.99") } { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : NumberDecimal("0.99") } 使用索引
{ price: 1 }的顺序,min()将查询限制在索引键边界为price等于1.39的文档,而max()将查询限制在索引键边界为price等于1.99的文档以下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") }