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.

API for MongoDB reference documentation | MongoDB Package (NuGet) packages/Microsoft.Azure.Cosmos) | Azure Developer CLI

Prerequisites

Setting up

Deploy this project's development container to your environment. Then, use the Azure Developer CLI (azd) to create an Azure Cosmos DB for MongoDB account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.

Open in GitHub Codespaces

Open in Dev Container

Important

GitHub accounts include an entitlement of storage and core hours at no cost. For more information, see included storage and core hours for GitHub accounts.

  1. Open a terminal in the root directory of the project.

  2. Authenticate to the Azure Developer CLI using azd auth login. Follow the steps specified by the tool to authenticate to the CLI using your preferred Azure credentials.

    azd auth login
    
  3. Use azd init to initialize the project.

    azd init --template cosmos-db-mongodb-nodejs-quickstart
    

    Note

    This quickstart uses the azure-samples/cosmos-db-mongodb-nodejs-quickstart template GitHub repository. The Azure Developer CLI will automatically clone this project to your machine if it is not already there.

  4. During initialization, configure a unique environment name.

    Tip

    The environment name will also be used as the target resource group name. For this quickstart, consider using msdocs-cosmos-db.

  5. Deploy the Azure Cosmos DB account using azd up. The Bicep templates also deploy a sample web application.

    azd up
    
  6. During the provisioning process, select your subscription and desired location. Wait for the provisioning process to complete. The process can take approximately five minutes.

  7. Once the provisioning of your Azure resources is done, a URL to the running web application is included in the output.

    Deploying services (azd deploy)
    
      (✓) Done: Deploying service web
    - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io>
    
    SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
    
  8. Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.

    Screenshot of the running web application.


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

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 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 might, or might 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 might 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 doesn'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 performed steps.

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.