Tip: Connecting to Azure Cosmos DB MongoDB API using the MongoDB Go driver
Tags: azure, mongodb, nosql, go
Published: 2020-03-26 17:55:01

[Azure Cosmos DB provides MongoDB API support](https://docs.microsoft.com/azure/cosmos-db/mongodb-introduction?WT.mc_id=devto-blog-abhishgu) which means that you can use a language specific driver to natively connect to Cosmos DB.

> There are lots of resources in the documentation e.g. [a Java quickstart](https://docs.microsoft.com/azure/cosmos-db/create-mongodb-java?WT.mc_id=devto-blog-abhishgu), [Node.js + React tutorial](https://docs.microsoft.com/azure/cosmos-db/tutorial-develop-mongodb-react?WT.mc_id=devto-blog-abhishgu) etc.

But what about [Golang](http://golang.org/), specifically, the official [MongoDB driver](https://github.com/mongodb/mongo-go-driver)? I expected it to "just work", but I faced a small issue. On a bad day, I might have spent hours and (probably) given up. Fortunately, that was not the case! Hopefully, this post can help you save some time in case you stumble across this 😉

![](https://media.giphy.com/media/26rVEQQqvw0aeAfBid/giphy.gif)

I started off by creating an Azure Cosmos DB account for MongoDB version `3.6` ([the other supported version is `3.2`](https://docs.microsoft.com/azure/cosmos-db/mongodb-feature-support?WT.mc_id=devto-blog-abhishgu)) and grabbed the [connection string from the portal](https://docs.microsoft.com/azure/cosmos-db/connect-mongodb-account?WT.mc_id=devto-blog-abhishgu). Here is the format:

```
mongodb://[COSMOSDB_ACCOUNT_NAME]:[PRIMARY_PASSWORD]@[COSMOSDB_ACCOUNT_NAME].mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@[COSMOSDB_ACCOUNT_NAME]@
```

![](https://dev-to-uploads.s3.amazonaws.com/i/qyfos2k3f4mwzyz5u5el.png)

> Note that at the time of writing, you can only [create MongoDB version `3.6` using the Azure portal (not the Azure CLI)](https://docs.microsoft.com/azure/cosmos-db/cli-samples-mongodb?WT.mc_id=devto-blog-abhishgu)

I used this simple program just to test the connectivity

```
package main

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

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

var connectionStr string

func init() {
	connectionStr = os.Getenv("MONGODB_CONNECTION_STRING")
	if connectionStr == "" {
		log.Fatal("Missing enviornment variable MONGODB_CONNECTION_STRING")
	}
}

func main() {

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	fmt.Println("connecting...")
	clientOptions := options.Client().ApplyURI(connectionStr)
	c, err := mongo.NewClient(clientOptions)

	err = c.Connect(ctx)

	if err != nil {
		log.Fatalf("unable to connect %v", err)
	}
	err = c.Ping(ctx, nil)
	if err != nil {
		log.Fatalf("unable to ping Cosmos DB %v", err)
	}

	fmt.Println("connected!")
}
```

To test, just set the connection string and run the program

```
export MONGODB_CONNECTION_STRING=<copy-paste from azure portal>

go run main.go
```

I expected to see `connected!` but this is what I got instead:

```
unable to Ping: connection(cdb-ms-prod-southeastasia1-cm1.documents.azure.com:10255[-5]) connection is closed
```

I started debugging based on an "educated guess". Azure Cosmos DB provides MongoDB support via [wire protocol compatibility](https://docs.microsoft.com/azure/cosmos-db/mongodb-introduction?WT.mc_id=devto-blog-abhishgu#wire-protocol-compatibility) and allows you to connect using a single endpoint (see the connection string). This means that you don't have to worry about the underlying database cluster topology.

Perhaps the driver is trying to "be smart" about this? I started looking at Mongo driver [`ClientOptions`](https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#ClientOptions) and its available methods more closely ,and there it was: the [`SetDirect`](https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#ClientOptions.SetDirect) method!

Here is the Godoc:

```
SetDirect specifies whether or not a direct connect should be made. To use this option, a URI with a single host must be specified through ApplyURI. If set to true, the driver will only connect to the host provided in the URI and will not discover other hosts in the cluster. This can also be set through the "connect" URI option with the following values:

1. "connect=direct" for direct connections

2. "connect=automatic" for automatic discovery.

The default is false ("automatic" in the connection string).
```

All I had to do was to update the `ClientOptions`

```
clientOptions := options.Client().ApplyURI(connectionStr).SetDirect(true)
```

> You can also add this to the connection string itself by appending `connect=direct` (as per Godoc) and I can confirm that it works as well

That's it. Now I was able to connect to Azure Cosmos DB MongoDB API 🙌 Stay tuned for an upcoming blog post where I will dive into MongoDB on Azure Cosmos DB + Go with the help of a practical example!