DEV Community

Abhishek Gupta for Microsoft Azure

Posted on

Tip: Connecting to Azure Cosmos DB MongoDB API using the MongoDB Go driver

Azure Cosmos DB provides MongoDB API support 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, Node.js + React tutorial etc.

But what about Golang, specifically, the official MongoDB 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 πŸ˜‰

I started off by creating an Azure Cosmos DB account for MongoDB version 3.6 (the other supported version is 3.2) and grabbed the connection string from the portal. Here is the format:

Enter fullscreen mode Exit fullscreen mode

Note that at the time of writing, you can only create MongoDB version 3.6 using the Azure portal (not the Azure CLI)

I used this simple program just to test the connectivity

package main

import (


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()

    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)

Enter fullscreen mode Exit fullscreen mode

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

export MONGODB_CONNECTION_STRING=<copy-paste from azure portal>

go run main.go
Enter fullscreen mode Exit fullscreen mode

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

unable to Ping: connection([-5]) connection is closed
Enter fullscreen mode Exit fullscreen mode

I started debugging based on an "educated guess". Azure Cosmos DB provides MongoDB support via 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 and its available methods more closely ,and there it was: the 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).
Enter fullscreen mode Exit fullscreen mode

All I had to do was to update the ClientOptions

clientOptions := options.Client().ApplyURI(connectionStr).SetDirect(true)
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

shaijut profile image
Shaiju T

Hi πŸ˜„, I would like to know What is the difference b/w MongoDB and CosmosDB , When one should prefer one over another ?

abhirockzz profile image
Abhishek Gupta

Great question! Azure Cosmos DB provides API compatibility with many NoSQL databases including MongoDB. The documentation should help clarify this in detail

In terms of preference/choice, the answer always is that "it depends". I would highly encourage you to go through the benefits which include turnkey, global distribution with multi-master replication etc. and the kind of solutions it's suitable for