Overview
在本指南中,您可以了解如何使用 Go 驱动程序运行数据库命令。 您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。
执行命令
要运行数据库命令,必须在命令文档中指定该命令和所有相关参数,然后将该命令文档传递给包装器方法。 命令文档必须是保序类型,例如 bson.D
。 Go 驱动程序提供以下方法来运行数据库命令:
RunCommand()
,将以SingleResult
类型返回命令响应。 您可以将此方法与任何数据库命令一起使用。RunCommandCursor()
,将以Cursor
类型返回命令响应。 如果数据库命令返回多个结果文档,则可以使用此方法。
以下代码展示如何使用RunCommand()
方法运行hello
命令,该命令会返回有关数据库中副本集中当前成员角色的信息:
command := bson.D{{"hello", 1}} var result bson.M err = db.RunCommand(context.TODO(), command).Decode(&result)
有关数据库命令和相应参数的完整列表,请参阅附加信息部分。
注意
读取偏好
RunCommand()
和RunCommandCursor()
不遵循您在代码其他地方可能为Database
对象设置的读取偏好(read preference)。您可以通过将对象传递给任一方法来设置命令执行的读取偏好(readRunCmdOptions
preference):
opts := options.RunCmd().SetReadPreference(readpref.Primary()) cursor, err := db.RunCommandCursor(context.TODO(), command, opts)
有关读取偏好(read preference)选项的更多信息,请参阅 读取和写入设置 基础知识页面。
响应
执行命令后,每个方法都会返回一个SingleResult
对象或游标,其中包含数据库的响应。 每个数据库命令执行不同的功能,因此响应内容可能因命令而异。 但是,每个响应都包含具有以下字段的文档:
字段 | 说明 |
---|---|
<command result> | 提供特定于数据库命令的字段。例如, |
| 表明命令是成功( |
| 指示操作的逻辑时间。 MongoDB使用逻辑时间对操作进行排序。 要学习;了解有关逻辑时间的更多信息,请参阅我们有关全局逻辑时钟的博文文。 |
| 提供返回签名集群时间的文档。 集群时间是用于操作排序的逻辑时间。 该文档包含以下字段:
|
例子
以下代码显示如何使用RunCommand()
explain
count
flowers
方法对db
数据库的collection运行 操作的 命令。explain
命令在"queryPlanner"
详细模式下运行:
db := client.Database("db") // Creates commands to count documents in a collection and explain // how the count command runs countCommand := bson.D{{"count", "flowers"}} explainCommand := bson.D{{"explain", countCommand}, {"verbosity", "queryPlanner"}} // Retrieves results of the explain command var result bson.M err = db.RunCommand(context.TODO(), explainCommand).Decode(&result)
输出
在输出中,您应该看到解释count
操作执行情况的字段,例如获胜计划,即查询优化器选择的计划,以及任何被拒绝的计划。输出还包含有关执行explain
命令的信息:
{ "$clusterTime": { "clusterTime": { "T": 1673969525, "I": 24 }, "signature": {...} }, "command": { "$db": "db", "count": "flowers" }, "explainVersion": "1", "ok": 1, "operationTime": { "T": 1673969525, "I": 24 }, "queryPlanner": { "indexFilterSet": false, "maxIndexedAndSolutionsReached": false, "maxIndexedOrSolutionsReached": false, "maxScansToExplodeReached": false, "namespace": "db.flowers", "rejectedPlans": [], "winningPlan": { "stage": "RECORD_STORE_FAST_COUNT" } }, "serverInfo": {...}, "serverParameters": { "internalDocumentSourceGroupMaxMemoryBytes": 104857600, ... } }
运行命令示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集中包含的 sample_restaurants
数据库。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下示例检索有关 sample_restaurants
数据库的统计信息:
// Runs a database command by using the Go driver package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() { db := client.Database("sample_restaurants") // Retrieves statistics about the specified database command := bson.D{{"dbStats", 1}} var result bson.M // Runs the command and prints the database statistics err := db.RunCommand(context.TODO(), command).Decode(&result) // Prints a message if any errors occur during the command execution if err != nil { panic(err) } /* When you run this file, it should print something similar to the following: { "avgObjSize": 548.4101901854896, "collections": 2, "dataSize": 14014074, "db": "sample_restaurants", "fileSize": 0, "indexSize": 286720, "indexes": 2, "nsSizeMB": 0, "numExtents": 0, "objects": 25554, "ok": 1, "storageSize": 8257536, "totalFreeStorageSize": 0, "views": 0 } */ output, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", output) } }
// results truncated { "avgObjSize": 548.4101901854896, "collections": 2, "dataSize": 14014074, "db": "sample_restaurants", "indexSize": 286720, ..., }
更多信息
有关本指南中概念的更多信息,请参阅以下文档:
要了解如何从游标检索数据,请参阅从游标访问数据基础知识页面。