How to obtain MongoDB version using Golang library?

Issue

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!

Solution

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

Answered By – icza

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.