对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

游标()(mongosh方法)

cursor.hint(index)

重要

mongosh 方法

This page documents a mongosh method. 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 对所有命令的支持的信息,请参阅不支持的命令

  • When an index filter exists for the query shape, MongoDB ignores the hint().

  • If a query includes a $text expression, you cannot use hint() 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.

  • 时间序列集合上,只能使用索引名称而不能使用索引键模式来指定提示。

  • 集群查询设置优先于作为命令字段传递的查询设置或索引提示。如果匹配的查询设置已包含索引提示,MongoDB将忽略命令字段中的索引提示。

    索引提示不会影响查询结构。

    有关提示和查询设置的更多信息,请参阅查询设置语法。

$natural

$naturalcursor.hint() 结合使用执行集合扫描,以按自然顺序返回文档。

有关用法,请参阅强制集合扫描。

注意

在MongoDB7.0 之前,$natural 接受不正确的类型值,例如0NaN 、“X”和-0.01 。在MongoDB. 之后,如果将7 01和 以外的任何值传递给-1 $natural, MongoDB将返回错误。

以下示例使用 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 } )
给本页内容打分