How to Connect to MongoDB from Go

Connect to MongoDB from Go using the official driver package and the mongo.Connect function with your URI.

Use the official go.mongodb.org/mongo-driver package to connect by creating a client with your connection string and calling Connect.

package main

import (
	"context"
	"log"

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

func main() {
	ctx := context.Background()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	_ = client
}