Quickstart: Use Node.js to connect and query data from Azure Cosmos DB SQL API account

APPLIES TO: SQL API

In this quickstart, you create and manage an Azure Cosmos DB SQL API account from the Azure portal, and by using a Node.js app cloned from GitHub. Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with global distribution and horizontal scale capabilities.

Walkthrough video

Watch this video for a complete walkthrough of the content in this article.

Prerequisites

Create an Azure Cosmos account

For this quickstart purpose, you can use the try Azure Cosmos DB for free option to create an Azure Cosmos account.

  1. Navigate to the try Azure Cosmos DB for free page.

  2. Choose the SQL API account and select Create. Sign-in using your Microsoft account.

  3. After the sign-in is successful, your Azure Cosmos account should be ready. Select Open in the Azure portal to open the newly created account.

The "try Azure Cosmos DB for free" option doesn't require an Azure subscription and it offers you an Azure Cosmos account for a limited period of 30 days. If you want to use the Azure Cosmos account for a longer period, you should instead create the account within your Azure subscription.

Add a container

You can now use the Data Explorer tool in the Azure portal to create a database and container.

  1. Select Data Explorer > New Container.

    The Add Container area is displayed on the far right, you may need to scroll right to see it.

    The Azure portal Data Explorer, Add Container pane

  2. In the Add container page, enter the settings for the new container.

    Setting Suggested value Description
    Database ID ToDoList Enter Tasks as the name for the new database. Database names must contain from 1 through 255 characters, and they cannot contain /, \\, #, ?, or a trailing space. Check the Share throughput across containers option, it allows you to share the throughput provisioned on the database across all the containers within the database. This option also helps with cost savings.
    Database throughput You can provision Autoscale or Manual throughput. Manual throughput allows you to scale RU/s yourself whereas autoscale throughput allows the system to scale RU/s based on usage. Select Manual for this example.

    Leave the throughput at 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later by estimating the required RU/s with the capacity calculator.

    Note: This setting is not available when creating a new container in a serverless account.
    Container ID Items Enter Items as the name for your new container. Container IDs have the same character requirements as database names.
    Partition key /category The sample described in this article uses /category as the partition key.

    Don't add Unique keys or turn on Analytical store for this example. Unique keys let you add a layer of data integrity to the database by ensuring the uniqueness of one or more values per partition key. For more information, see Unique keys in Azure Cosmos DB. Analytical store is used to enable large-scale analytics against operational data without any impact to your transactional workloads.

    Select OK. The Data Explorer displays the new database and container.

Add sample data

You can now add data to your new container using Data Explorer.

  1. From the Data Explorer, expand the Tasks database, expand the Items container. Select Items, and then select New Item.

    Create new documents in Data Explorer in the Azure portal

  2. Now add a document to the container with the following structure.

    {
        "id": "1",
        "category": "personal",
        "name": "groceries",
        "description": "Pick up apples and strawberries.",
        "isComplete": false
    }
    
  3. Once you've added the json to the Documents tab, select Save.

    Copy in json data and select Save in Data Explorer in the Azure portal

  4. Create and save one more document where you insert a unique value for the id property, and change the other properties as you see fit. Your new documents can have any structure you want as Azure Cosmos DB doesn't impose any schema on your data.

Query your data

You can use queries in Data Explorer to retrieve and filter your data.

  1. At the top of the Items tab in Data Explorer, review the default query SELECT * FROM c. This query retrieves and displays all documents from the container ordered by ID.

    Default query in Data Explorer is SELECT * FROM c

  2. To change the query, select Edit Filter, replace the default query with ORDER BY c._ts DESC, and then select Apply Filter.

    Change the default query by adding ORDER BY c._ts DESC and clicking Apply Filter

    The modified query displays the documents in descending order based on their time stamp, so now your second document is listed first.

    Changed query to ORDER BY c._ts DESC and clicking Apply Filter

If you're familiar with SQL syntax, you can enter any supported SQL queries in the query predicate box. You can also use Data Explorer to create stored procedures, UDFs, and triggers for server-side business logic.

Data Explorer provides easy Azure portal access to all of the built-in programmatic data access features available in the APIs. You also use the portal to scale throughput, get keys and connection strings, and review metrics and SLAs for your Azure Cosmos DB account.

Clone the sample application

Now let's clone a Node.js app from GitHub, set the connection string, and run it.

  1. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-sql-api-nodejs-getting-started.git
    

Review the code

This step is optional. If you're interested in learning how the Azure Cosmos database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to Update your connection string.

If you're familiar with the previous version of the SQL JavaScript SDK, you may be used to seeing the terms collection and document. Because Azure Cosmos DB supports multiple API models, version 2.0+ of the JavaScript SDK uses the generic terms container, which may be a collection, graph, or table, and item to describe the content of the container.

The Cosmos DB JavaScript SDK is called "@azure/cosmos" and can be installed from npm...

npm install @azure/cosmos

The following snippets are all taken from the app.js file.

  • The CosmosClient is imported from the @azure/cosmos npm package.

    const CosmosClient = require("@azure/cosmos").CosmosClient;
    
  • A new CosmosClient object is initialized.

    const client = new CosmosClient({ endpoint, key });
    
  • Select the "Tasks" database.

    const database = client.database(databaseId);
    
  • Select the "Items" container/collection.

    const container = database.container(containerId);
    
  • Select all the items in the "Items" container.

    // query to return all items
    const querySpec = {
      query: "SELECT * from c"
    };
    
    const { resources: items } = await container.items
      .query(querySpec)
      .fetchAll();
    
  • Create a new item

    const { resource: createdItem } = await container.items.create(newItem);
    
  • Update an item

    const { id, category } = createdItem;
    
    createdItem.isComplete = true;
    const { resource: updatedItem } = await container
      .item(id, category)
      .replace(createdItem);
    
  • Delete an item

    const { resource: result } = await container.item(id, category).delete();
    

Note

In both the "update" and "delete" methods, the item has to be selected from the database by calling container.item(). The two parameters passed in are the id of the item and the item's partition key. In this case, the parition key is the value of the "category" field.

Update your connection string

Now go back to the Azure portal to get the connection string details of your Azure Cosmos account. Copy the connection string into the app so that it can connect to your database.

  1. In your Azure Cosmos DB account in the Azure portal, select Keys from the left navigation, and then select Read-write Keys. Use the copy buttons on the right side of the screen to copy the URI and Primary Key into the app.js file in the next step.

    View and copy an access key in the Azure portal, Keys blade

  2. In Open the config.js file.

  3. Copy your URI value from the portal (using the copy button) and make it the value of the endpoint key in config.js.

    endpoint: "<Your Azure Cosmos account URI>"

  4. Then copy your PRIMARY KEY value from the portal and make it the value of the config.key in config.js. You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

    key: "<Your Azure Cosmos account key>"

Run the app

  1. Run npm install in a terminal to install the "@azure/cosmos" npm package

  2. Run node app.js in a terminal to start your node application.

  3. The two items that you created earlier in this quickstart are listed out. A new item is created. The "isComplete" flag on that item is updated to "true" and then finally, the item is deleted.

You can continue to experiment with this sample application or go back to Data Explorer, modify, and work with your data.

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.

Next steps

In this quickstart, you've learned how to create an Azure Cosmos DB account, create a container using the Data Explorer, and run a Node.js app. You can now import additional data to your Azure Cosmos DB account.

Trying to do capacity planning for a migration to Azure Cosmos DB? You can use information about your existing database cluster for capacity planning.