Quickstart: Build a console app using Azure Cosmos DB's API for MongoDB and Golang SDK

Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. You can quickly create and query document, key/value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Cosmos DB.

This quickstart demonstrates how to take an existing MongoDB app written in Golang and connect it to your Cosmos database using the Azure Cosmos DB's API for MongoDB.

In other words, your Golang application only knows that it's connecting using a MongoDB client. It is transparent to the application that the data is stored in a Cosmos database.


  • An Azure subscription. If you don’t have an Azure subscription, create a free account before you begin.

    Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. Or you can use the Azure Cosmos DB Emulator for this tutorial with a connection string of

  • Go and a basic knowledge of the Go language.

  • An IDE — GoLand by Jetbrains, Visual Studio Code by Microsoft, or Atom. In this tutorial, I'm using GoLand.

Create a database account

  1. In a new window, sign in to the Azure portal.

  2. In the left menu, select Create a resource, select Databases, and then under Azure Cosmos DB, select Create.

    Screenshot of the Azure portal, highlighting More Services, and Azure Cosmos DB

  3. In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same unique name as provided in ID
    Select Create new. Then enter a new resource-group name for your account. For simplicity, use the same name as your ID.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because mongo.cosmos.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can use only lowercase letters, numbers, and the hyphen (-) character. It must be between 3 and 31 characters in length.
    API Azure Cosmos DB's API for MongoDB The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB's API MongoDB for document databases, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Select MongoDB because in this quickstart you are creating a collection that works with MongoDB.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
    Version 3.6 Select the MongoDB wire protocol version 3.6 or for backwards compatibility, select 3.2.

    Select Review+Create. You can skip the Network and Tags section.

    The new account page for Azure Cosmos DB

  4. The account creation takes a few minutes. Wait for the portal to display the Congratulations! Your Cosmos account with wire protocol compatibility for MongoDB is ready page.

    The Azure portal Notifications pane

Clone the sample application

Clone the sample application and install the required packages.

  1. Create a folder named CosmosDBSample inside the GOROOT\src folder, which is C:\Go\ by default.

  2. Run the following command using a git terminal window such as git bash to clone the sample repository into the CosmosDBSample folder.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-mongodb-golang-getting-started.git
  3. Run the following command to get the mgo package.

    go get gopkg.in/mgo.v2

The mgo driver is a MongoDB driver for the Go language that implements a rich and well tested selection of features under a very simple API following standard Go idioms.

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. Click Quick start in the left navigation menu, and then click Other to view the connection string information required by the Go application.

  2. In Goglang, open the main.go file in the GOROOT\CosmosDBSample directory and update the following lines of code using the connection string information from the Azure portal as shown in the following screenshot.

    The Database name is the prefix of the Host value in the Azure portal connection string pane. For the account shown in the image below, the Database name is golang-coach.

    Database: "The prefix of the Host value in the Azure portal",
    Username: "The Username in the Azure portal",
    Password: "The Password in the Azure portal",

    Quick start pane, Other tab in the Azure portal showing the connection string information

  3. Save the main.go file.

Review the code

This step is optional. If you're interested in learning how the database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to Run the app.

The following snippets are all taken from the main.go file.

Connecting the Go app to Cosmos DB

Azure Cosmos DB's API for MongoDB supports the SSL-enabled connection. To connect, you need to define the DialServer function in mgo.DialInfo, and make use of the tls.Dial function to perform the connection.

The following Golang code snippet connects the Go app with Azure Cosmos DB's API for MongoDB. The DialInfo class holds options for establishing a session.

// DialInfo holds options for establishing a session.
dialInfo := &mgo.DialInfo{
    Addrs:    []string{"golang-couch.documents.azure.com:10255"}, // Get HOST + PORT
    Timeout:  60 * time.Second,
    Database: "database", // It can be anything
    Username: "username", // Username
    Password: "Azure database connect password from Azure Portal", // PASSWORD
    DialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {
        return tls.Dial("tcp", addr.String(), &tls.Config{})

// Create a session which maintains a pool of socket connections
// to Cosmos database (using Azure Cosmos DB's API for MongoDB).
session, err := mgo.DialWithInfo(dialInfo)

if err != nil {
    fmt.Printf("Can't connect, go error %v\n", err)

defer session.Close()

// SetSafe changes the session safety mode.
// If the safe parameter is nil, the session is put in unsafe mode, 
// and writes become fire-and-forget,
// without error checking. The unsafe mode is faster since operations won't hold on waiting for a confirmation.

The mgo.Dial() method is used when there is no SSL connection. For an SSL connection, the mgo.DialWithInfo() method is required.

An instance of the DialWIthInfo{} object is used to create the session object. Once the session is established, you can access the collection by using the following code snippet:

collection := session.DB("database").C("package")

Create a document

// Model
type Package struct {
    Id bson.ObjectId  `bson:"_id,omitempty"`
    FullName      string
    Description   string
    StarsCount    int
    ForksCount    int
    LastUpdatedBy string

// insert Document in collection
err = collection.Insert(&Package{
    Description:"A framework for building native apps with React.",
    ForksCount: 11392,


if err != nil {
    log.Fatal("Problem inserting data: ", err)

Query or read a document

Cosmos DB supports rich queries against data stored in each collection. The following sample code shows a query that you can run against the documents in your collection.

// Get a Document from the collection
result := Package{}
err = collection.Find(bson.M{"fullname": "react"}).One(&result)
if err != nil {
    log.Fatal("Error finding record: ", err)

fmt.Println("Description:", result.Description)

Update a document

// Update a document
updateQuery := bson.M{"_id": result.Id}
change := bson.M{"$set": bson.M{"fullname": "react-native"}}
err = collection.Update(updateQuery, change)
if err != nil {
    log.Fatal("Error updating record: ", err)

Delete a document

Cosmos DB supports deletion of documents.

// Delete a document
query := bson.M{"_id": result.Id}
err = collection.Remove(query)
if err != nil {
   log.Fatal("Error deleting record: ", err)

Run the app

  1. In Golang, ensure that your GOPATH (available under File, Settings, Go, GOPATH) include the location in which the gopkg was installed, which is USERPROFILE\go by default.

  2. Comment out the lines that delete the document, lines 103-107, so that you can see the document after running the app.

  3. In Golang, click Run, and then click Run 'Build main.go and run'.

    The app finishes and displays the description of the document created in Create a document.

    Description: A framework for building native apps with React.
    Process finished with exit code 0

    Golang showing the output of the app

Review your document in Data Explorer

Go back to the Azure portal to see your document in Data Explorer.

  1. Click Data Explorer (Preview) in the left navigation menu, expand golang-coach, package, and then click Documents. In the Documents tab, click the _id to display the document in the right pane.

    Data Explorer showing the newly created document

  2. You can then work with the document inline and click Update to save it. You can also delete the document, or create new documents or queries.

Review SLAs in the Azure portal

The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:

  1. In the Azure portal, select Resource groups on the far left. If the left menu is collapsed, select Expand button to expand it.

  2. Select the resource group you created for this quickstart.

    Select the resource group to delete

  3. In the new window, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

In this quickstart, you've learned how to create a Cosmos account and run a Golang app. You can now import additional data to your Cosmos database.