How to Use the Official MongoDB Driver for Go

Install and use the official go.mongodb.org/mongo-driver package to connect your Go application to MongoDB.

The official MongoDB driver for Go is go.mongodb.org/mongo-driver, which you install via go get and import into your code.

package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)

	// Verify connection
	if err = client.Ping(ctx, nil); err != nil {
		log.Fatal(err)
	}
	log.Println("Connected to MongoDB!")
}