定义
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:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
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()运行数据库命令。
未指定读取偏好的 hello 命令
此示例演示如何使用 db.runCommand() 来运行 hello 命令。
db.runCommand( { hello: 1 } )
有关输出的详细信息,请参阅 hello 输出。
有关读取偏好行为的详细信息,请参阅读取偏好。
带以下 readPreference 的 hello 命令:secondaryPreferred
此示例说明如何使用db.runCommand() hello运行具有secondaryPreferred 读取偏好的命令。
db.runCommand( { hello: 1 }, { readPreference: "secondaryPreferred" } )
有关输出的详细信息,请参阅 hello 输出。
有关读取偏好行为的详细信息,请参阅读取偏好。
响应
该方法返回包含以下字段的响应文档:
字段 | 说明 |
|---|---|
<command result> | 特定于运行的 |
| 表明命令成功 ( |
| 操作的逻辑时间。MongoDB 使用逻辑时间对排序操作。仅适用于副本集和分片集群。 如果命令不生成 oplog 条目,例如读操作,则该操作不会推进逻辑时钟。在这种情况下,
对于与因果一致会话相关的操作,MongoDB 驱动程序使用逻辑时间自动设置读取操作和 |
| 返回已签名集群时间的文档。集群时间是用于操作排序的逻辑时间。仅适用于副本集和分片集群。仅供内部使用。 该文档包含以下字段:
|