cursor.hint()
On this page本页内容
Definition定义
cursor.hint(index)
- Important
mongosh Method
This page documents a本页记录了一个mongosh
method. This is not the documentation for a language-specific driver, such as Node.js.mongosh
方法。这不是针对特定语言驱动程序(如Node.js)的文档。For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档。Call this method on a query to override MongoDB's default index selection and query optimization process.对查询调用此方法以覆盖MongoDB的默认索引选择和查询优化过程。Use使用db.collection.getIndexes()
to return the list of current indexes on a collection.db.collection.getIndexes()
返回集合上的当前索引列表。Thecursor.hint()
method has the following parameter:cursor.hint()
方法具有以下参数:Parameter参数Type类型Description描述index
string or document The index to "hint" or force MongoDB to use when performing the query. Specify the index either by the index name or by the index specification document.执行查询时要“提示”或强制MongoDB使用的索引。通过索引名称或索引规范文档指定索引。
You can also specify您还可以指定{ $natural : 1 }
to force the query to perform a forwards collection scan, or{ $natural : -1 }
for a reverse collection scan.{ $natural : 1 }
以强制查询执行正向集合扫描,或者指定{ $natural : -1 }
以执行反向集合扫描。
Behavior行为
When an index filter exists for the query shape, MongoDB ignores the当查询形状存在索引筛选器时,MongoDB会忽略hint()
.hint()
。If a query includes a如果查询包含$text
expression, you cannot usehint()
to specify which index to use for the query.$text
表达式,则不能使用hint()
指定用于查询的索引。If you use如果对隐藏索引或不存在的索引使用hint()
on a hidden index or an index that doesn't exist, the operation returns an error.hint()
,则操作将返回错误。On a time series collections, you can only specify hints using the index name, not the index key pattern.在时间序列集合中,只能使用索引名称而不是索引键模式指定提示。
Examples实例
Specify an Index指定索引
The following example returns all documents in the collection named 以下示例使用users
using the index on the age
field.age
字段上的索引返回集合中名为users
的所有文档。
db.users.find().hint( { age: 1 } )
You can also specify the index using the index name:也可以使用索引名称指定索引:
db.users.find().hint( "age_1" )
Force Collection Scans强制集合扫描
You can specify 您可以指定{ $natural : 1 }
to force the query to perform a forwards collection scan:{ $natural : 1 }
以强制查询执行转发集合扫描:
db.users.find().hint( { $natural : 1 } )
You can also specify 您还可以指定{ $natural : -1 }
to force the query to perform a reverse collection scan{ $natural : -1 }
以强制查询执行反向集合扫描:
db.users.find().hint( { $natural : -1 } )