cursor.min()

在本页面

Definition

  • cursor. min ( )
    • 指定特定索引的(包括)下限,以约束find()的结果。 min()提供了一种在复合键索引上指定下限的方法。

min()方法具有以下参数:

ParameterTypeDescription
indexBoundsdocument索引键的包含性下限。

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

如果您使用min()max()来指定范围:

  • min()max()中指定的索引范围必须都引用同一索引的键。

  • max()指定的边界必须大于min()指定的边界。

在版本 3.6.6 中进行了更改。

min()没有 max()

minmax运算符指示系统应避免常规查询计划。相反,它们构造索引扫描,其中索引范围由minmax中给出的值明确指定。

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等于appletype等于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的索引键边界以下的文档:

Note

在版本 3.6.6 中更改:max()指定的界限必须大于min()指定的界限。

db.products.find().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )

该查询返回以下文档:

{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }