运行命令
Overview
在本指南中,您可以学习;了解如何使用Kotlin Sync驾驶员运行数据库命令。您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。
重要
首选驱动程序方法而非数据库命令
驱动程序为许多数据库命令提供了封装方法。我们建议尽可能使用驱动程序方法,而不是执行数据库命令。
要执行管理任务,请使用 MongoDB Shell 而不是Kotlin Sync驾驶员。在Shell内调用 db.runCommand()
方法是发出数据库命令的首选方法,因为它在Shell和驱动程序之间提供了一致的接口。
执行命令
要运行数据库命令,请在文档中指定该命令和所有相关参数,然后将该文档传递给 runCommand()
方法。
以下代码展示了如何使用 runCommand()
方法运行explain
命令,该命令会返回 find
命令在调用后将如何执行的说明:
val commandToExplain = Document("find", "restaurants") val explanation = database.runCommand(Document("explain", commandToExplain))
有关数据库命令和相应参数的完整列表,请参阅 数据库命令指南。
命令选项
您可以通过包含 readPreference
参数来指定 runCommand()
方法的可选命令行为。以下示例展示了如何指定读取偏好(read preference)并将其作为选项传递给 runCommand()
方法:
val command = Document("hello", 1) val commandReadPreference = Document("readPreference", "secondary") val commandResult = database.runCommand(command, commandReadPreference)
有关读取偏好选项的更多信息,请参阅 MongoDB Server手册中的 读取偏好 。
注意
runCommand()
方法会忽略您可能对 database
对象设立的读取偏好(read preference)设置。如果未指定读取偏好(read preference),则此方法使用 primary
读取偏好(read preference)。
响应
执行命令后,runCommand()
方法会返回一个 Document
对象,其中包含数据库的响应。 每个数据库命令执行不同的功能,因此响应内容可能因命令而异。 但是,每个响应都包含具有以下字段的文档:
字段 | 说明 |
---|---|
<command result> | 提供特定于数据库命令的字段。例如, |
| 表明命令是成功( |
| 指示操作的逻辑时间。 MongoDB使用逻辑时间对操作进行排序。 要学习;了解有关逻辑时间的更多信息,请参阅我们有关全局逻辑时钟的博文文。 |
| 提供返回签名集群时间的文档。 集群时间是用于操作排序的逻辑时间。 该文档包含以下字段:
|
例子
以下示例展示了如何运行buildInfo
命令及其生成的输出:
import com.mongodb.MongoException import com.mongodb.kotlin.client.MongoClient import org.bson.Document import org.bson.BsonInt64 import org.bson.json.JsonWriterSettings fun main() { // Replace the placeholder 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 = Document("buildInfo", 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() }
{ version: '8.0.4', ...<other command results>... ok: 1, '$clusterTime': { clusterTime: Timestamp({ ... }), signature: { ... } }, operationTime: Timestamp({ ... }) }
更多信息
有关本指南中概念的更多信息,请参阅以下文档: