Edit

Share via


Quickstart: Use Azure DocumentDB with MongoDB driver for Node.js

In this quickstart, you create a basic Azure DocumentDB application using Node.js. 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 Node.js.

API reference | Source code | Package (npm)

Prerequisites

  • An Azure subscription

    • If you don't have an Azure subscription, create a free account
  • Node.js 22 or newer

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 Node.js project in your current directory.

  1. Start in an empty directory.

  2. Open a terminal in the current directory.

  3. Initialize a Node.js project.

    npm init -y
    
  4. Install TypeScript and initialize TypeScript configuration (optional for TypeScript support).

    npm install -D typescript @types/node
    npx tsc --init
    

Install the client library

The client library is available through npm, as the mongodb package.

  1. Install the MongoDB Node.js driver using npm.

    npm install mongodb
    
  2. Open and review the package.json file to validate that the package entry exists.

  3. Import the required modules into your application code:

    import { MongoClient, Db, Collection, Document } from 'mongodb';
    
    const { MongoClient } = require('mongodb');
    

Object model

Name Description
MongoClient Type used to connect to MongoDB.
Db Represents a database in the cluster.
Collection<Document> 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.

    async function main(): Promise<void> {
        // Connection string for Azure DocumentDB cluster
        const 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 a new client and connect to the server
        const client = new MongoClient(connectionString);
    
    async function main() {
        // Connection string for Azure DocumentDB cluster
        const 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 a new client and connect to the server
        const client = new MongoClient(connectionString);
    
  2. Connect to the MongoDB client and verify the connection.

        try {
            // Connect to the MongoDB cluster
            await client.connect();
    
            // Ping the server to verify connection
            await client.db("admin").command({ ping: 1 });
            console.log("Successfully connected and pinged Azure DocumentDB");
    
        try {
            // Connect to the MongoDB cluster
            await client.connect();
    
            // Ping the server to verify connection
            await client.db("admin").command({ ping: 1 });
            console.log("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
            const database: Db = client.db("adventureworks");
            console.log(`Connected to database: ${database.databaseName}`);
    
            // Get database reference
            const database = client.db("adventureworks");
            console.log(`Connected to database: ${database.databaseName}`);
    
  2. Get a reference to the collection within the database.

            // Get collection reference
            const collection: Collection<Document> = database.collection("products");
            console.log("Connected to collection: products");
    
            // Get collection reference
            const collection = database.collection("products");
            console.log("Connected to collection: products");
    

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. Create sample product documents.

            // Create sample products
            interface Product {
                _id: string;
                name: string;
                category: string;
                quantity: number;
                price: number;
                sale: boolean;
            }
    
            const 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,
                }
            ];
    
            // Create sample products
            const products = [
                {
                    _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 (const product of products) {
                const filter = { _id: product._id };
                const options = { upsert: true };
    
                await collection.replaceOne(filter, product, options);
                console.log(`Upserted product: ${product.name}`);
            }
    
            // Insert documents with upsert
            for (const product of products) {
                const filter = { _id: product._id };
                const options = { upsert: true };
    
                await collection.replaceOne(filter, product, options);
                console.log(`Upserted product: ${product.name}`);
            }
    

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
            const filter = { _id: "00000000-0000-0000-0000-000000004018" };
    
            // Retrieve a specific document by ID
            const filter = { _id: "00000000-0000-0000-0000-000000004018" };
    
  2. Execute the query and retrieve the result.

            const retrievedProduct = await collection.findOne(filter);
    
            if (retrievedProduct) {
                console.log(`Retrieved product: ${retrievedProduct.name} - $${retrievedProduct.price}`);
            } else {
                console.log("Product not found");
            }
    
            const retrievedProduct = await collection.findOne(filter);
    
            if (retrievedProduct) {
                console.log(`Retrieved product: ${retrievedProduct.name} - $${retrievedProduct.price}`);
            } else {
                console.log("Product not found");
            }
    

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
            const saleFilter = { sale: true };
            const saleProducts = await collection.find(saleFilter).toArray();
    
            // Query for products on sale
            const saleFilter = { sale: true };
            const saleProducts = await collection.find(saleFilter).toArray();
    
  2. Iterate through the results to display the matching documents.

            console.log("Products on sale:");
            for (const product of saleProducts) {
                console.log(`- ${product.name}: $${product.price.toFixed(2)} (Category: ${product.category})`);
            }
    
        } catch (error) {
            console.error("An error occurred:", error);
        } finally {
            await client.close();
        }
    }
    
    main().catch(console.error);
    
            console.log("Products on sale:");
            for (const product of saleProducts) {
                console.log(`- ${product.name}: $${product.price.toFixed(2)} (Category: ${product.category})`);
            }
    
        } catch (error) {
            console.error("An error occurred:", error);
        } finally {
            await client.close();
        }
    }
    
    main().catch(console.error);
    

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.