Quickstart: Azure Cosmos DB for MongoDB driver for Node.js

APPLIES TO: MongoDB

Get started with the MongoDB npm package to create databases, collections, and docs within your Azure Cosmos DB resource. Follow these steps to install the package and try out example code for basic tasks.

Note

The example code snippets are available on GitHub as a JavaScript project.

API for MongoDB reference documentation | MongoDB Package (NuGet)

Prerequisites

Prerequisite check

  • In a terminal or command window, run node --version to check that Node.js is one of the LTS versions.
  • Run az --version (Azure CLI) or Get-Module -ListAvailable AzureRM (Azure PowerShell) to check that you have the appropriate Azure command-line tools installed.

Setting up

This section walks you through creating an Azure Cosmos DB account and setting up a project that uses the MongoDB npm package.

Create an Azure Cosmos DB account

This quickstart will create a single Azure Cosmos DB account using the API for MongoDB.

  1. Create shell variables for accountName, resourceGroupName, and location.

    # Variable for resource group name
    resourceGroupName="msdocs-cosmos-quickstart-rg"
    location="westus"
    
    # Variable for account name with a randomnly generated suffix
    let suffix=$RANDOM*$RANDOM
    accountName="msdocs-$suffix"
    
  2. If you haven't already, sign in to the Azure CLI using the az login command.

  3. Use the az group create command to create a new resource group in your subscription.

    az group create \
        --name $resourceGroupName \
        --location $location
    
  4. Use the az cosmosdb create command to create a new Azure Cosmos DB for MongoDB account with default settings.

    az cosmosdb create \
        --resource-group $resourceGroupName \
        --name $accountName \
        --locations regionName=$location
        --kind MongoDB
    

Get MongoDB connection string

  1. Find the API for MongoDB connection string from the list of connection strings for the account with the az cosmosdb keys list command.

    az cosmosdb keys list --type connection-strings \
        --resource-group $resourceGroupName \
        --name $accountName 
    
  2. Record the PRIMARY KEY values. You'll use these credentials later.

Create a new JavaScript app

Create a new JavaScript application in an empty folder using your preferred terminal. Use the npm init command to begin the prompts to create the package.json file. Accept the defaults for the prompts.

npm init

Install the package

Add the MongoDB npm package to the JavaScript project. Use the npm install package command specifying the name of the npm package. The dotenv package is used to read the environment variables from a .env file during local development.

npm install mongodb dotenv

Configure environment variables

To use the CONNECTION STRING values within your code, set this value in the local environment running the application. To set the environment variable, use your preferred terminal to run the following commands:

$env:COSMOS_CONNECTION_STRING = "<cosmos-connection-string>"

Object model

Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB. Azure Cosmos DB has a specific object model used to create and access resources. The Azure Cosmos DB creates resources in a hierarchy that consists of accounts, databases, collections, and docs.

Diagram of the Azure Cosmos DB hierarchy including accounts, databases, collections, and docs.

Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database shards. One of the database shards includes two child collection shards. The other database shard includes a single child collection node. That single collection shard has three child doc shards.

You'll use the following MongoDB classes to interact with these resources:

  • MongoClient - This class provides a client-side logical representation for the API for MongoDB layer on Azure Cosmos DB. The client object is used to configure and execute requests against the service.
  • Db - This class is a reference to a database that may, or may not, exist in the service yet. The database is validated server-side when you attempt to access it or perform an operation against it.
  • Collection - This class is a reference to a collection that also may not exist in the service yet. The collection is validated server-side when you attempt to work with it.

Code examples

The sample code described in this article creates a database named adventureworks with a collection named products. The products collection is designed to contain product details such as name, category, quantity, and a sale indicator. Each product also contains a unique identifier.

For this procedure, the database won't use sharding.

Authenticate the client

  1. From the project directory, create an index.js file. In your editor, add requires statements to reference the MongoDB and DotEnv npm packages.

    // Read .env file and set environment variables
    require('dotenv').config();
    const random = Math.floor(Math.random() * 100);
    
    // Use official mongodb driver to connect to the server
    const { MongoClient, ObjectId } = require('mongodb');
    
  2. Define a new instance of the MongoClient, class using the constructor, and process.env. to read the environment variable you created earlier.

    // New instance of MongoClient with connection string
    // for Cosmos DB
    const url = process.env.COSMOS_CONNECTION_STRING;
    const client = new MongoClient(url);
    

For more information on different ways to create a MongoClient instance, see MongoDB NodeJS Driver Quick Start.

Set up asynchronous operations

In the index.js file, add the following code to support the asynchronous operations:

async function main(){

// The remaining operations are added here
// in the main function

}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

The following code snippets should be added into the main function in order to handle the async/await syntax.

Connect to the database

Use the MongoClient.connect method to connect to your Azure Cosmos DB for MongoDB resource. The connect method returns a reference to the database.

// Use connect method to connect to the server
await client.connect();

Get database instance

Use the MongoClient.db gets a reference to a database.

// Database reference with creation if it does not already exist
const db = client.db(`adventureworks`);
console.log(`New database:\t${db.databaseName}\n`);

Get collection instance

The MongoClient.Db.collection gets a reference to a collection.

// Collection reference with creation if it does not already exist
const collection = db.collection('products');
console.log(`New collection:\t${collection.collectionName}\n`);

Chained instances

You can chain the client, database, and collection together. Chaining is more convenient if you need to access multiple databases or collections.

const db = await client.db(`adventureworks`).collection('products').updateOne(query, update, options)

Create an index

Use the Collection.createIndex to create an index on the document's properties you intend to use for sorting with the MongoDB's FindCursor.sort method.

// create index to sort by name
const indexResult = await collection.createIndex({ name: 1 });
console.log(`indexResult: ${JSON.stringify(indexResult)}\n`);

Create a doc

Create a doc with the product properties for the adventureworks database:

  • An _id property for the unique identifier of the product.
  • A category property. This property can be used as the logical partition key.
  • A name property.
  • An inventory quantity property.
  • A sale property, indicating whether the product is on sale.
// Create new doc and upsert (create or replace) to collection
const product = {
    category: "gear-surf-surfboards",
    name: `Yamba Surfboard-${random}`,
    quantity: 12,
    sale: false
};
const query = { name: product.name};
const update = { $set: product };
const options = {upsert: true, new: true};

// Insert via upsert (create or replace) doc to collection directly
const upsertResult1 = await collection.updateOne(query, update, options);
console.log(`upsertResult1: ${JSON.stringify(upsertResult1)}\n`);

// Update via upsert on chained instance
const query2 = { _id: ObjectId(upsertResult1.upsertedId) };
const update2 = { $set: { quantity: 20 } };
const upsertResult2 = await client.db(`adventureworks`).collection('products').updateOne(query2, update2, options);
console.log(`upsertResult2: ${JSON.stringify(upsertResult2)}\n`);

Create an doc in the collection by calling Collection.UpdateOne. In this example, we chose to upsert instead of create a new doc in case you run this sample code more than once.

Get a doc

In Azure Cosmos DB, you can perform a less-expensive point read operation by using both the unique identifier (_id) and partition key (category).

// Point read doc from collection:
// - without sharding, should use {_id}
// - with sharding,    should use {_id, partitionKey }, ex: {_id, category}
const foundProduct = await collection.findOne({
    _id: ObjectId(upsertResult1.upsertedId), 
    category: "gear-surf-surfboards"
});
console.log(`foundProduct: ${JSON.stringify(foundProduct)}\n`);

Query docs

After you insert a doc, you can run a query to get all docs that match a specific filter. This example finds all docs that match a specific category: gear-surf-surfboards. Once the query is defined, call Collection.find to get a FindCursor result. Convert the cursor into an array to use JavaScript array methods.

// select all from product category
const allProductsQuery = { 
    category: "gear-surf-surfboards" 
};

// get all documents, sorted by name, convert cursor into array
const products = await collection.find(allProductsQuery).sort({name:1}).toArray();
products.map((product, i ) => console.log(`${++i} ${JSON.stringify(product)}`));

Troubleshooting:

  • If you get an error such as The index path corresponding to the specified order-by item is excluded., make sure you created the index.

Run the code

This app creates an API for MongoDB database and collection and creates a doc and then reads the exact same doc back. Finally, the example issues a query that should only return that single doc. With each step, the example outputs information to the console about the steps it has performed.

To run the app, use a terminal to navigate to the application directory and run the application.

node index.js

The output of the app should be similar to this example:

New database:   adventureworks

New collection: products

upsertResult1: {"acknowledged":true,"modifiedCount":0,"upsertedId":"62b1f492ff69395b30a03169","upsertedCount":1,"matchedCount":0}

upsertResult2: {"acknowledged":true,"modifiedCount":1,"upsertedId":null,"upsertedCount":0,"matchedCount":1}

foundProduct: {"_id":"62b1f492ff69395b30a03169","name":"Yamba Surfboard-93","category":"gear-surf-surfboards","quantity":20,"sale":false}

indexResult: "name_1"

1 {"_id":"62b1f47dacbf04e86c8abf25","name":"Yamba Surfboard-11","category":"gear-surf-surfboards","quantity":20,"sale":false}
done

Clean up resources

When you no longer need the Azure Cosmos DB for MongoDB account, you can delete the corresponding resource group.

Use the az group delete command to delete the resource group.

az group delete --name $resourceGroupName

Next steps

In this quickstart, you learned how to create an Azure Cosmos DB for MongoDB account, create a database, and create a collection using the MongoDB driver. You can now dive deeper into the Azure Cosmos DB for MongoDB to import more data, perform complex queries, and manage your Azure Cosmos DB MongoDB resources.