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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Microsoft Azure Cosmos Database Service
  • Data Pipeline Using MongoDB and Kafka Connect on Kubernetes
  • Azure Cosmos DB — A to Z
  • Leveraging AI and Vector Search in Azure Cosmos DB for MongoDB vCore

Trending

  • Javac and Java Katas, Part 1: Class Path
  • OpenID Connect Flows: From Implicit to Authorization Code With PKCE and BFF
  • Documenting a Spring REST API Using Smart-doc
  • How To Use Thread.sleep() in Selenium
  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
Like (5)
Save
Tweet
Share
9.6K 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

  • Microsoft Azure Cosmos Database Service
  • Data Pipeline Using MongoDB and Kafka Connect on Kubernetes
  • Azure Cosmos DB — A to Z
  • Leveraging AI and Vector Search in Azure Cosmos DB for MongoDB vCore

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: