如何使用Golang库获取MongoDB版本?

发布于 2025-01-17 01:33:28 字数 868 浏览 0 评论 0原文

我正在使用 Go 的 MongodDB 驱动程序 (https ://pkg.go.dev/go.mongodb.org/[email protected]/mongo#section-documentation)并希望获取部署的 mongoDB 服务器的版本。

例如,如果它是 MySQL 数据库,我可以执行如下操作:

db, err := sql.Open("mysql", DbUser+":"+DbPwd+"@tcp("+Host+")/"+DbName)
if err != nil {
    log.Printf("Error while connecting to DB: %v", err)
}
defer db.Close()

var dbVersion string
if err := db.QueryRow("SELECT VERSION()").Scan(&dbVersion); err != nil {
    dbVersion = "NA"
    log.Printf("Couldnt obtain db version: %w", err)
}
fmt.Println("DB Version: ", dbVersion)

我浏览了文档,但找不到线索。

我还需要获取其他元数据,例如特定数据库的大小等。

任何帮助将不胜感激。谢谢!

I am using Go's MongodDB driver (https://pkg.go.dev/go.mongodb.org/[email protected]/mongo#section-documentation) and want to obtain the version of the mongoDB server deployed.

For instance, if it would been a MySQL database, I can do something like below:

db, err := sql.Open("mysql", DbUser+":"+DbPwd+"@tcp("+Host+")/"+DbName)
if err != nil {
    log.Printf("Error while connecting to DB: %v", err)
}
defer db.Close()

var dbVersion string
if err := db.QueryRow("SELECT VERSION()").Scan(&dbVersion); err != nil {
    dbVersion = "NA"
    log.Printf("Couldnt obtain db version: %w", err)
}
fmt.Println("DB Version: ", dbVersion)

I went through the documentation but am not able to find a clue.

I also need to fetch other metadata like Size of a particular database etc.

Any help would be appreciated. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终陌 2025-01-24 01:33:28

MongoDB版本可以通过运行命令来获取,特别是buildInfo 命令

使用 shell,您可以这样做:

db.runCommand({buildInfo: 1})

结果是一个文档,其 version 属性保存服务器版本,例如:

{
    "version" : "5.0.6",
    ...
}

要使用官方驱动程序运行命令,请使用 Database.RunCommand() 方法。

例如:

// Connect to MongoDB and acquire a Database:

ctx := context.Background()
opts := options.Client().ApplyURI("mongodb://localhost")
client, err := mongo.Connect(ctx, opts)
if err != nil {
    log.Fatalf("Failed to connect to db: %v", err)
}
defer client.Disconnect(ctx)

db := client.Database("your-db-name")

// And now run the buildInfo command:

buildInfoCmd := bson.D{bson.E{Key: "buildInfo", Value: 1}}
var buildInfoDoc bson.M
if err := db.RunCommand(ctx, buildInfoCmd).Decode(&buildInfoDoc); err != nil {
    log.Printf("Failed to run buildInfo command: %v", err)
    return
}
log.Println("Database version:", buildInfoDoc["version"])

The MongoDB version can be acquired by running a command, specifically the buildInfo command.

Using the shell, this is how you could do it:

db.runCommand({buildInfo: 1})

The result is a document whose version property holds the server version, e.g.:

{
    "version" : "5.0.6",
    ...
}

To run commands using the official driver, use the Database.RunCommand() method.

For example:

// Connect to MongoDB and acquire a Database:

ctx := context.Background()
opts := options.Client().ApplyURI("mongodb://localhost")
client, err := mongo.Connect(ctx, opts)
if err != nil {
    log.Fatalf("Failed to connect to db: %v", err)
}
defer client.Disconnect(ctx)

db := client.Database("your-db-name")

// And now run the buildInfo command:

buildInfoCmd := bson.D{bson.E{Key: "buildInfo", Value: 1}}
var buildInfoDoc bson.M
if err := db.RunCommand(ctx, buildInfoCmd).Decode(&buildInfoDoc); err != nil {
    log.Printf("Failed to run buildInfo command: %v", err)
    return
}
log.Println("Database version:", buildInfoDoc["version"])
葬シ愛 2025-01-24 01:33:28

根据@icza的回答,以下是如何获取数据库的其他元数据:

我们需要使用 dbStats 命令获取元数据。

host := "<your-host-name>:<pot-number>"
url := "mongodb://" + host


credential := options.Credential{
    AuthSource: "authentication-database",
    Username:   "username",
    Password:   "password",
}

clientOpts := options.Client().ApplyURI(url).SetAuth(credential)

ctx := context.Background()
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
    log.Fatal("Failed to connect to db : %w", err)
}
defer client.Disconnect(ctx)

if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
    panic(err)
}
fmt.Println("Successfully connected and pinged.")

db := client.Database("your-database-name")


dbStatsCmd := bson.D{bson.E{Key: "dbStats", Value: 1}}
var dbStatsDoc bson.M
if err := db.RunCommand(ctx, dbStatsCmd).Decode(&dbStatsDoc); err != nil {
    log.Printf("Failed to run dbStats command: %v", err)
    return
}

log.Println("\nTotal Used Size in MB: ", dbStatsDoc["totalSize"].(float64) / 1048576 , " ,Total Free size in MB (part of total used size): ", dbStatsDoc["totalFreeStorageSize"].(float64)/1048576)

Based on @icza's answer, here is how to obtain other metadata of the Database:

We need to use dbStats command to obtain metadata.

host := "<your-host-name>:<pot-number>"
url := "mongodb://" + host


credential := options.Credential{
    AuthSource: "authentication-database",
    Username:   "username",
    Password:   "password",
}

clientOpts := options.Client().ApplyURI(url).SetAuth(credential)

ctx := context.Background()
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
    log.Fatal("Failed to connect to db : %w", err)
}
defer client.Disconnect(ctx)

if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
    panic(err)
}
fmt.Println("Successfully connected and pinged.")

db := client.Database("your-database-name")


dbStatsCmd := bson.D{bson.E{Key: "dbStats", Value: 1}}
var dbStatsDoc bson.M
if err := db.RunCommand(ctx, dbStatsCmd).Decode(&dbStatsDoc); err != nil {
    log.Printf("Failed to run dbStats command: %v", err)
    return
}

log.Println("\nTotal Used Size in MB: ", dbStatsDoc["totalSize"].(float64) / 1048576 , " ,Total Free size in MB (part of total used size): ", dbStatsDoc["totalFreeStorageSize"].(float64)/1048576)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文