定义
cursor.hint(index)重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for a language-specific driver, such as Node.js.如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
对查询调用此方法可覆盖 MongoDB 的默认索引选择和查询优化过程。使用
db.collection.getIndexes()返回集合的当前索引列表。The
cursor.hint()method has the following parameter:Parameter类型说明index字符串或文档
执行查询时“提示”或强制 MongoDB 使用的索引。通过索引名称或索引规范文档来指定索引。
您还可以指定
{ $natural : 1 }强制查询,以执行正向集合扫描,或指定{ $natural : -1 },以执行反向集合扫描。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
When an index filter exists for the query shape, MongoDB ignores the
hint().If a query includes a
$textexpression, you cannot usehint()to specify which index to use for the query.If you use
hint()on a hidden index or an index that doesn't exist, the operation returns an error.在时间序列集合上,只能使用索引名称而不能使用索引键模式来指定提示。
$natural
将 $natural 与 cursor.hint() 结合使用执行集合扫描,以按自然顺序返回文档。
有关用法,请参阅强制集合扫描。
示例
指定索引
以下示例使用 age 字段上的索引返回名为 users 的集合中的所有文档。
db.users.find().hint( { age: 1 } )
您还可以使用索引名称指定索引:
db.users.find().hint( "age_1" )
强制集合扫描
您可以指定 { $natural : 1 } 以强制查询执行正向集合扫描:
db.users.find().hint( { $natural : 1 } )
您还可指定 { $natural : -1 } 以强制查询执行反向集合扫描:
db.users.find().hint( { $natural : -1 } )