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

huangapple go评论96阅读模式
英文:

How to obtain MongoDB version using Golang library?

问题

我正在使用Go的MongoDB驱动程序(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("连接到数据库时出错:%v", err)
}
defer db.Close()

var dbVersion string
if err := db.QueryRow("SELECT VERSION()").Scan(&dbVersion); err != nil {
	dbVersion = "NA"
	log.Printf("无法获取数据库版本:%w", err)
}
fmt.Println("数据库版本:", dbVersion)

我已经查阅了文档,但没有找到线索。

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

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

英文:

I am using Go's MongodDB driver (https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.8.0/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!

答案1

得分: 3

MongoDB的版本可以通过运行命令来获取,具体来说是buildInfo命令

使用shell,你可以这样做:

db.runCommand({buildInfo: 1})

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

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

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

例如:

// 连接到MongoDB并获取一个数据库:

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")

// 现在运行buildInfo命令:

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("数据库版本:", 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"])

答案2

得分: 1

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

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

host := "<your-host-name>:<port-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 := &quot;&lt;your-host-name&gt;:&lt;pot-number&gt;&quot;
url := &quot;mongodb://&quot; + host


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

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

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

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

db := client.Database(&quot;your-database-name&quot;)


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

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

huangapple
  • 本文由 发表于 2022年3月25日 20:03:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/71616694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定