DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Maximize the Azure Cosmos DB Availability
  • Microsoft Azure Cosmos Database Service
  • Leveraging AI and Vector Search in Azure Cosmos DB for MongoDB vCore
  • Reference Architecture: Deploying WSO2 API Manager on Microsoft Azure

Trending

  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  1. DZone
  2. Data Engineering
  3. Databases
  4. Connecting to Azure Cosmos DB MongoDB API

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.

By 
Abhishek Gupta user avatar
Abhishek Gupta
DZone Core CORE ·
Jul. 31, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
10.4K Views

Join the DZone community and get the full member experience.

Join For Free

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
 




xxxxxxxxxx
1


 
1
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]@



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!

Cosmos DB API azure MongoDB Cosmos (operating system) Database

Opinions expressed by DZone contributors are their own.

Related

  • How to Maximize the Azure Cosmos DB Availability
  • Microsoft Azure Cosmos Database Service
  • Leveraging AI and Vector Search in Azure Cosmos DB for MongoDB vCore
  • Reference Architecture: Deploying WSO2 API Manager on Microsoft Azure

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook