{{announcement.body}}
{{announcement.title}}

Connecting to Azure Cosmos DB MongoDB API

DZone 's Guide to

Connecting to Azure Cosmos DB MongoDB API

Azure Cosmos DB provides MongoDB API support which means that you can use a language-specific driver to natively connect to Cosmos DB.

· Web Dev Zone ·
Free Resource

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 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:

Plain Text
 







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.

Java
 




xxxxxxxxxx
1
43


 
1
package main
2
 
          
3
import (
4
    "context"
5
    "fmt"
6
    "log"
7
    "os"
8
    "time"
9
 
          
10
    "go.mongodb.org/mongo-driver/mongo"
11
    "go.mongodb.org/mongo-driver/mongo/options"
12
)
13
 
          
14
var connectionStr string
15
 
          
16
func init() {
17
    connectionStr = os.Getenv("MONGODB_CONNECTION_STRING")
18
    if connectionStr == "" {
19
        log.Fatal("Missing enviornment variable MONGODB_CONNECTION_STRING")
20
    }
21
}
22
 
          
23
func main() {
24
 
          
25
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
26
    defer cancel()
27
 
          
28
    fmt.Println("connecting...")
29
    clientOptions := options.Client().ApplyURI(connectionStr)
30
    c, err := mongo.NewClient(clientOptions)
31
 
          
32
    err = c.Connect(ctx)
33
 
          
34
    if err != nil {
35
        log.Fatalf("unable to connect %v", err)
36
    }
37
    err = c.Ping(ctx, nil)
38
    if err != nil {
39
        log.Fatalf("unable to ping Cosmos DB %v", err)
40
    }
41
 
          
42
    fmt.Println("connected!")
43
}



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 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:

Java
 




xxxxxxxxxx
1


 
1
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:
2
 
          
3
1. "connect=direct" for direct connections
4
 
          
5
2. "connect=automatic" for automatic discovery.
6
 
          
7
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!

Topics:
azure, azure cosmos db, cloud, mongodb, nosql, tutorial, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}