Go

Connect a Go application to TeselaDB with the official MongoDB driver.

Connect a Go application to TeselaDB with the official MongoDB driver for Go. TeselaDB presents itself as a mongos, so the driver works unchanged.

Requirements

  • Go with modules.
  • The address of one or more nodes, a user with readWrite on the database and the pki/ca.pem file of the cluster.

Install the driver

Shell
go get go.mongodb.org/mongo-driver/v2/mongo

Store the connection string

Put the string in an environment variable instead of writing it in the code:

Shell
export TESELADB_URI="mongodb://user:<password>@node-01:27017,node-02:27017/shop?tls=true&tlsCAFile=./ca.pem"

Write and read a document

Go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

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

func main() {
	client, err := mongo.Connect(options.Client().ApplyURI(os.Getenv("TESELADB_URI")))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.Background())

	orders := client.Database("shop").Collection("orders")
	if _, err := orders.InsertOne(context.Background(), bson.M{"total": 149.5}); err != nil {
		log.Fatal(err)
	}
	count, err := orders.CountDocuments(context.Background(), bson.M{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(count)
}

Check

The program prints the number of documents in orders, which grows by one each time you run it.

Common problems

  • The connection closes before authenticating because tls=true is missing from the string.
  • The driver does not trust the node certificate because it does not have the CA of this cluster.

See also