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

运行数据库命令

在本指南中,您可以学习如何使用Kotlin驱动程序运行数据库命令。您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。

重要

首选驱动程序方法而非数据库命令

驱动程序为许多数据库命令提供了封装方法。我们建议尽可能使用驱动程序方法,而不是执行数据库命令。

To perform administrative tasks, use the MongoDB Shell instead of the Kotlin driver. Calling the db.runCommand() method inside the shell is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers.

要运行数据库命令,请在文档中指定该命令和所有相关参数,然后将该文档传递给 runCommand() 方法。

以下代码显示如何使用 runCommand() 方法运行dbStats 命令,该命令会从指定MongoDB 数据库返回统计信息:

注意

此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接指南。

import com.mongodb.MongoException
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.BsonDocument
import org.bson.BsonInt64
import org.bson.json.JsonWriterSettings
fun main() = runBlocking {
// Replace the uri string with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
try {
val command = BsonDocument("dbStats", BsonInt64(1))
val commandResult = database.runCommand(command)
println(commandResult.toJson(JsonWriterSettings.builder().indent(true).build()))
} catch (me: MongoException) {
System.err.println("An error occurred: $me")
}
mongoClient.close()
}

有关数据库命令和相应参数的完整列表,请参阅 数据库命令指南。

您可以通过包含 readPreference 参数来指定 runCommand() 方法的可选命令行为。以下示例展示了如何指定读取偏好(read preference)并将其作为选项传递给 runCommand() 方法:

val command = Document("hello", 1)
val commandReadPreference = Document("readPreference", "secondary")
val result = database.runCommand(command, commandReadPreference)

有关读取偏好选项的更多信息,请参阅 MongoDB Server手册中的 读取偏好 。

注意

runCommand() 方法会忽略您可能对 database对象设立的读取偏好(read preference)设置。如果未指定读取偏好(read preference),则此方法使用 primary读取偏好(read preference)。

执行命令后,runCommand() 方法会返回一个 Document对象,其中包含数据库的响应。 每个数据库命令执行不同的功能,因此响应内容可能因命令而异。 但是,每个响应都包含具有以下字段的文档:

字段
说明

<command result>

提供特定于数据库命令的字段。例如, count返回n字段, explain返回queryPlanner字段。

ok

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

operationTime

指示操作的逻辑时间。MongoDB使用逻辑时间对操作进行排序。要学习有关逻辑时间的更多信息,请参阅我们关于全局逻辑时钟的博客文章。

$clusterTime

提供返回签名集群时间的文档。集群时间是用于排序操作的逻辑时间。

该文档包含以下字段:

  • clusterTime:节点的已知最高集群时间的时间戳

  • signature:包含集群时间哈希以及用于对集群时间进行签名的密钥ID的文档

有关本指南中概念的更多信息,请参阅以下文档: