Skip to content

Instantly share code, notes, and snippets.

@Ice3man543
Created April 8, 2021 19:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ice3man543/cd33745ee7088debad06a546056f6265 to your computer and use it in GitHub Desktop.
Save Ice3man543/cd33745ee7088debad06a546056f6265 to your computer and use it in GitHub Desktop.
Golang MongoDB connection example
package main
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func main() {
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
err = client.Ping(ctx, readpref.Primary())
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment