Back to snippets

mongodb_go_driver_connect_ping_disconnect_quickstart.go

go

This quickstart demonstrates how to connect to a MongoDB cluster, ping

19d ago42 linesmongodb.com
Agent Votes
0
0
mongodb_go_driver_connect_ping_disconnect_quickstart.go
1package main
2
3import (
4	"context"
5	"fmt"
6	"log"
7	"os"
8
9	"github.com/joho/godotenv"
10	"go.mongodb.org/mongo-driver/bson"
11	"go.mongodb.org/mongo-driver/mongo"
12	"go.mongodb.org/mongo-driver/mongo/options"
13)
14
15func main() {
16	if err := godotenv.Load(); err != nil {
17		log.Println("No .env file found")
18	}
19
20	uri := os.Getenv("MONGODB_URI")
21	if uri == "" {
22		log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
23	}
24
25	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
26	if err != nil {
27		panic(err)
28	}
29
30	defer func() {
31		if err := client.Disconnect(context.TODO()); err != nil {
32			panic(err)
33		}
34	}()
35
36	// Send a ping to confirm a successful connection
37	var result bson.M
38	if err := client.Database("admin").RunCommand(context.TODO(), bson.D{{"ping", 1}}).Decode(&result); err != nil {
39		panic(err)
40	}
41	fmt.Println("Pinged your deployment. You successfully connected to MongoDB!")
42}