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

db.runCommand()(mongosh方法)

db.runCommand(command, [options])

提供运行指定数据库命令的辅助程序。这是发出数据库命令的首选方法,因为它在 Shell 和驱动程序之间提供了一致的接口。

Parameter
类型
说明

command

文档或字符串

指定该命令的文档或字符串。如果指定为字符串,db.runCommand() 会将该字符串转换为文档。

options

文档

从 mongosh 2.0 开始,系指指定 mongosh 如何运行命令的选项。

options.readPreference

读取运行命令的读取偏好。若未指定,则默认为 primary。 db.runCommand() 忽略任何其他读取偏好全局配置集,包括使用 setReadPref() 或在连接字符串中指定 readPreference。

在 mongosh 1.x 中, db.runCommand() 不接受 options 参数。要设置读取偏好,请使用 Mongo.setReadPref() 或在连接字符串中指定 readPreference 。

要指定以毫秒为单位的时间限制,请参阅终止正在运行的操作。

此方法可用于以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

注意

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.

db.runCommand() runs the command in the context of the current database. Some commands are only applicable in the context of the admin database, and you must change your db object before running these commands or use db.adminCommand().

Starting in mongosh 2.0, you can specify the read preference for a command with the options argument. If you do not specify a read preference, db.runCommand() defaults to primary.

警告

在 mongosh 2.0 中,db.runCommand() 忽略任何其他读取偏好全局配置集,包括使用 Mongo.setReadPref() 或在连接字符串中指定 readPreference。

在 mongosh 1.x 中,db.runCommand()不接受options参数。通过使用Mongo.setReadPref()或在连接字符串中指定readPreference,db.runCommand()使用指定的读取偏好。

以下示例演示如何使用db.runCommand()运行数据库命令。

此示例演示如何使用 db.runCommand() 来运行 hello 命令。

db.runCommand( { hello: 1 } )

有关输出的详细信息,请参阅 hello 输出。

For details on read preference behavior, see Read Preference.

此示例说明如何使用db.runCommand() hello运行具有secondaryPreferred 读取偏好的命令。

db.runCommand( { hello: 1 }, { readPreference: "secondaryPreferred" } )

有关输出的详细信息,请参阅 hello 输出。

For details on read preference behavior, see Read Preference.

该方法返回包含以下字段的响应文档:

字段
说明

<command result>

特定于运行的 command 结果字段。

ok

表明命令成功 (1) 还是失败 (0) 的数字。

operationTime

操作的逻辑时间。MongoDB 使用逻辑时间对排序操作。仅适用于副本集和分片集群。

如果命令不生成 oplog 条目,例如读操作,则该操作不会推进逻辑时钟。在这种情况下,operationTime 会返回:

对于与因果一致会话相关的操作,MongoDB 驱动程序使用逻辑时间自动设置读取操作和 afterClusterTime 周期。

$clusterTime

返回已签名集群时间的文档。集群时间是用于操作排序的逻辑时间。仅适用于副本集和分片集群。仅供内部使用。

该文档包含以下字段:

  • clusterTime:成员的已知最高集群时间的时间戳。

  • signature:一个文档,包含集群时间的哈希值和用于对集群时间进行签名的密钥 ID。

给本页内容打分