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
Newsletter
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 IoT Time-Series Applications With Java and Apache IoTDB
  • Event Sourcing in Distributed Systems: Architecture, Consistency, and Fault-Tolerant Projections
  • Data Integration Landscape 2026: Event Streaming, API, and Batch in the Era of Agentic AI
  • How to Build Your Own AI SRE From Scratch

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Jul. 31, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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