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.

Prerequisites

  • 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

    mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true
    
  • 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, click Create a resource, click Databases, and then under Azure Cosmos DB, click 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 documents.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 table that works with the 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.

    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)
    os.Exit(1)
}

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.
// 
session.SetSafe(&mgo.Safe{})

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{
    FullName:"react",
    Description:"A framework for building native apps with React.",
    ForksCount: 11392,
    StarsCount:48794,
    LastUpdatedBy:"shergin",

})

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

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)
    return
}

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)
    return
}

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)
   return
}

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 throughput, storage, availability, latency, and consistency of the resources in your account are monitored in the Azure portal. Let's take a quick look at these metrics.

  1. Click Metrics in the navigation menu.

    Metrics in the Azure portal

  2. Click through each of the tabs so you're aware of the metrics Azure Cosmos DB provides.

    Each chart that's associated with the Azure Cosmos DB Service Level Agreements (SLAs) provides a line that shows if any of the SLAs have been violated. Azure Cosmos DB makes monitoring your SLAs transparent with this suite of metrics.

    Azure Cosmos DB metrics suite

Clean up resources

If you're not going to continue to use this app, delete all resources created by this quickstart with the following steps so you don't incur any charges:

  1. In the Azure portal, select Resource groups on the far left, and then select the resource group you created.

    If the left menu is collapsed, click Expand button to expand it.

    Metrics in the Azure portal

  2. In the new window select the resource group, and then click Delete resource group.

    Metrics in the Azure portal

  3. In the new window, type the name of the resource group to delete, and then click 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.