Skip to content

Connect Mongo Client

Ken Chen edited this page May 19, 2019 · 5 revisions

Connect

Examples to connect to a mongo cluster using mongo-go-driver.

Mongo Shell

$ mongo "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin"

Connect Using a Connection URI

uri := "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin"
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
	fmt.Println(err.Error())
}

Connect Using Options

opts := options.Client()
opts.SetHosts([]string{"localhost:27017"})
auth := options.Credential{Username: "user", Password: "password", AuthSource: "admin"}
opts.SetAuth(auth)
opts.SetReplicaSet("replset")
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
	fmt.Println(err.Error())
}

Connect with TLS Encryption

Mongo Shell

$ mongo "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin" \
    --sslCAFile ca.crt --sslPEMKeyFile client.pem

Connect Using a Connection URI

uri := "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin"
opts := options.Client().ApplyURI(uri)
caBytes, _ := ioutil.ReadFile("ca.crt")
clientBytes, _ := ioutil.ReadFile("client.pem")
roots := x509.NewCertPool()
if ok := roots.AppendCertsFromPEM(caBytes); !ok {
	return errors.New("failed to parse root certificate")
}
certs, err := tls.X509KeyPair(clientBytes, clientBytes)
if err != nil {
	return err
}
cfg := &tls.Config{RootCAs: roots, Certificates: []tls.Certificate{certs}}
opts.SetTLSConfig(cfg)
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
	fmt.Println(err.Error())
}