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

我正在使用 Go 的 MongodDB 驱动程序 ( https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.8.0/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)

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


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


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


皈依舞
浏览 128回答 2
2回答

呼如林

MongoDB 版本可以通过运行命令获取,具体为buildInfocommand。使用 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.Mif 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"])

有只小跳蛙

我们需要使用dbStats命令来获取元数据。host := "<your-host-name>:<pot-number>"url := "mongodb://" + hostcredential := options.Credential{&nbsp; &nbsp; AuthSource: "authentication-database",&nbsp; &nbsp; Username:&nbsp; &nbsp;"username",&nbsp; &nbsp; Password:&nbsp; &nbsp;"password",}clientOpts := options.Client().ApplyURI(url).SetAuth(credential)ctx := context.Background()client, err := mongo.Connect(ctx, clientOpts)if err != nil {&nbsp; &nbsp; log.Fatal("Failed to connect to db : %w", err)}defer client.Disconnect(ctx)if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {&nbsp; &nbsp; 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.Mif err := db.RunCommand(ctx, dbStatsCmd).Decode(&dbStatsDoc); err != nil {&nbsp; &nbsp; log.Printf("Failed to run dbStats command: %v", err)&nbsp; &nbsp; 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)
打开App,查看更多内容
随时随地看视频慕课网APP