Edit

Share via


Quickstart: Use Azure DocumentDB with MongoDB driver for Go

In this quickstart, you create a basic Azure DocumentDB application using Go. Azure DocumentDB is a NoSQL data store that allows applications to store documents in the cloud and access them using official MongoDB drivers. This guide shows how to create documents and perform basic tasks in your Azure DocumentDB cluster using Go.

API reference | Source code | Package (Go)

Prerequisites

  • An Azure subscription

    • If you don't have an Azure subscription, create a free account
  • Golang 1.18 or later

Create an Azure DocumentDB cluster

To get started, you first need to create an Azure DocumentDB cluster, which serves as the foundation for storing and managing your NoSQL data.

  1. Sign in to the Azure portal (https://portal.azure.com).

  2. From the Azure portal menu or the Home page, select Create a resource.

  3. On the New page, search for and select Azure DocumentDB.

    Screenshot showing search for Azure DocumentDB.

  4. On the Create Azure DocumentDB cluster page and within the Basics section, select the Configure option within the Cluster tier section.

    Screenshot showing Configure cluster option.

  5. On the Scale page, configure these options and then select Save to persist your changes to the cluster tier.

    Value
    Cluster tier M30 tier, 2 vCore, 8-GiB RAM
    Storage per shard 128 GiB

    Screenshot of configuration options for compute and storage for a new Azure DocumentDB cluster.

  6. Back in the Basics section, configure the following options:

    Value
    Subscription Select your Azure subscription
    Resource group Create a new resource group or select an existing resource group
    Cluster name Provide a globally unique name
    Location Select a supported Azure region for your subscription
    MongoDB version Select 8.0
    Admin username Create a username to access the cluster as a user administrator
    Password Use a unique password associated with the username

    Screenshot showing cluster parameters.

    Tip

    Record the values you use for username and password. These values are used later in this guide. For more information about valid values, see cluster limitations.

  7. Select Next: Networking.

  8. In the Firewall rules section on the Networking tab, configure these options:

    Value
    Connectivity method Public access
    Allow public access from Azure services and resources within Azure to this cluster Enabled
  9. Add a firewall rule for your current client device to grant access to the cluster by selecting + Add current client IP address.

    Screenshot showing network configurations.

    Tip

    In many corporate environments, developer machine IP addresses are hidden due to a VPN or other corporate network settings. In these cases, you can temporarily allow access to all IP addresses by adding the 0.0.0.0 - 255.255.255.255 IP address range as a firewall rule. Use this firewall rule only temporarily as a part of connection testing and development.

  10. Select Review + create.

  11. Review the settings you provide, and then select Create. It takes a few minutes to create the cluster. Wait for the resource deployment is complete.

  12. Finally, select Go to resource to navigate to the Azure DocumentDB cluster in the portal.

Screenshot showing goto resource options.

Get cluster credentials

Get the credentials you use to connect to the cluster.

  1. On the cluster page, select the Connection strings option in the resource menu.

  2. In the Connection strings section, copy or record the value from the Connection string field.

Screenshot showing connection strings option.

Important

The connection string in the portal doesn't include the password value. You must replace the <password> placeholder with the credentials you entered when you created the cluster or enter the password interactively.

Initialize the project

Create a new Go module in your current directory.

  1. Start in an empty directory.

  2. Open a terminal in the current directory.

  3. Initialize a new Go module.

    go mod init azure-documentdb-go-quickstart
    

Install the client library

The client library is available through Go, as the go.mongodb.org/mongo-driver/v2/mongo module.

  1. Install the MongoDB Go driver using go get.

    go get go.mongodb.org/mongo-driver/v2/mongo
    
  2. Create a new Go file named main.go for your application code.

  3. Import the required packages into your application code:

    import (
        "context"
        "fmt"
        "log"
        "time"
    
        "go.mongodb.org/mongo-driver/v2/bson"
        "go.mongodb.org/mongo-driver/v2/mongo"
        "go.mongodb.org/mongo-driver/v2/mongo/options"
    )
    

Object model

Name Description
mongo.Client Type used to connect to MongoDB.
mongo.Database Represents a database in the cluster.
mongo.Collection Represents a collection within a database in the cluster.

Code examples

The code in this application connects to a database named adventureworks and a collection named products. The products collection contains details such as name, category, quantity, a unique identifier, and a sale flag for each product. The code samples here perform the most common operations when working with a collection.

Authenticate the client

First, connect to the client using a basic connection string.

  1. Create the main function and set up the connection string. Replace <your-cluster-name>, <your-username>, and <your-password> with your actual cluster information.

    func main() {
        // Connection string for Azure DocumentDB cluster
        connectionString := "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"
    
        // Create client options
        clientOptions := options.Client().ApplyURI(connectionString)
    
  2. Connect to the MongoDB client and verify the connection.

        // Create a new client and connect to the server
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()
    
        client, err := mongo.Connect(ctx, clientOptions)
        if err != nil {
            log.Fatal(err)
        }
        defer client.Disconnect(ctx)
    
        // Ping the primary
        err = client.Ping(ctx, nil)
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println("Successfully connected and pinged Azure DocumentDB")
    

Get a collection

Now, get your database and collection. If the database and collection doesn't already exist, use the driver to create it for you automatically.

  1. Get a reference to the database.

        // Get database reference
        database := client.Database("adventureworks")
        fmt.Println("Connected to database:", database.Name())
    
  2. Get a reference to the collection within the database.

        // Get collection reference
        collection := database.Collection("products")
        fmt.Println("Connected to collection:", collection.Name())
    

Create a document

Then, create a couple of new documents within your collection. Upsert the documents to ensure that it replaces any existing documents if they already exist with the same unique identifier.

  1. Define a product type and create sample product documents.

        type Product struct {
            ID       string  `bson:"_id,omitempty"`
            Name     string  `bson:"name"`
            Category string  `bson:"category"`
            Quantity int     `bson:"quantity"`
            Price    float64 `bson:"price"`
            Sale     bool    `bson:"sale"`
        }
    
        // Create sample products
        products := []Product{
            {
                ID:       "00000000-0000-0000-0000-000000004018",
                Name:     "Windry Mittens",
                Category: "apparel-accessories-gloves-and-mittens",
                Quantity: 121,
                Price:    35.00,
                Sale:     false,
            },
            {
                ID:       "00000000-0000-0000-0000-000000004318",
                Name:     "Niborio Tent",
                Category: "gear-camp-tents",
                Quantity: 140,
                Price:    420.00,
                Sale:     true,
            },
        }
    
  2. Insert the documents using upsert operations.

        // Insert documents with upsert
        for _, product := range products {
            filter := bson.M{"_id": product.ID}
            update := bson.M{"$set": product}
            opts := options.Update().SetUpsert(true)
    
            result, err := collection.UpdateOne(ctx, filter, update, opts)
            if err != nil {
                log.Fatal(err)
            }
    
            if result.UpsertedID != nil {
                fmt.Printf("Inserted document with ID: %v\n", result.UpsertedID)
            } else {
                fmt.Printf("Updated document with ID: %s\n", product.ID)
            }
        }
    

Retrieve a document

Next, perform a point read operation to retrieve a specific document from your collection.

  1. Define the filter to find a specific document by ID.

        // Retrieve a specific document by ID
        filter := bson.M{"_id": "00000000-0000-0000-0000-000000004018"}
        var retrievedProduct Product
    
  2. Execute the query and decode the result.

        err = collection.FindOne(ctx, filter).Decode(&retrievedProduct)
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Printf("Retrieved product: %+v\n", retrievedProduct)
    

Query documents

Finally, query multiple documents using the MongoDB Query Language (MQL).

  1. Define a query to find documents matching specific criteria.

        // Query for products on sale
        queryFilter := bson.M{"sale": true}
        cursor, err := collection.Find(ctx, queryFilter)
        if err != nil {
            log.Fatal(err)
        }
        defer cursor.Close(ctx)
    
  2. Iterate through the cursor to retrieve all matching documents.

        fmt.Println("Products on sale:")
        for cursor.Next(ctx) {
            var product Product
            if err := cursor.Decode(&product); err != nil {
                log.Fatal(err)
            }
            fmt.Printf("- %s: $%.2f (Category: %s)\n", product.Name, product.Price, product.Category)
        }
    
        if err := cursor.Err(); err != nil {
            log.Fatal(err)
        }
    }
    

Explore your data using Visual Studio Code

Use the DocumentDB extension in Visual Studio Code to perform core database operations, including querying, inserting, updating, and deleting data.

  1. Open Visual Studio Code.

  2. Navigate to the Extensions view and search for the term DocumentDB. Locate the DocumentDB for VS Code extension.

  3. Select the Install button for the extension. Wait for the installation to complete. Reload Visual Studio Code if prompted.

  4. Navigate to the DocumentDB extension by selecting the corresponding icon in the Activity Bar.

  5. In the DocumentDB Connections pane, select + New Connection....

  6. In the dialog, select Service Discovery and then Azure DocumentDB - Azure Service Discovery.

  7. Select your Azure subscription and your newly created Azure DocumentDB cluster.

    Tip

    In many corporate environments, developer machine IP addresses are hidden due to a VPN or other corporate network settings. In these cases, you can temporarily allow access to all IP addresses by adding the 0.0.0.0 - 255.255.255.255 IP address range as a firewall rule. Use this firewall rule only temporarily as a part of connection testing and development. For more information, see configure firewall.

  8. Back in the DocumentDB Connections pane, expand the node for your cluster and navigate to your existing document and collection nodes.

  9. Open the context menu for the collection and then select DocumentDB Scrapbook > New DocumentDB Scrapbook.

  10. Enter the following MongoDB Query Language (MQL) commands and then select Run All. Observe the output from the commands.

    db.products.find({
      price: { $gt: 200 },
      sale: true
    })
    .sort({ price: -1 })
    .limit(3)
    

Clean up resources

When you're done with the Azure DocumentDB cluster, you can delete the Azure resources you created so you don't incur more charges.

  1. In the Azure portal search bar, search for and select Resource groups.

    Screenshot showing option for searching resource groups.

  2. In the list, select the resource group you used for this quickstart.

    Screenshot showing resource group.

  3. On the resource group page, select Delete resource group.

  4. In the deletion confirmation dialog, enter the name of the resource group to confirm that you intend to delete it. Finally, select Delete to permanently delete the resource group.

    Screenshot showing delete resource group confirmation button.