MongoDB with Go

Connect to MongoDB in Go using the official driver and the ApplyURI method.

Use the official go.mongodb.org/mongo-driver package to connect to MongoDB from Go.

import "go.mongodb.org/mongo-driver/mongo"

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

if err = client.Ping(ctx, nil); err != nil {
    log.Fatal(err)
}