Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
APPLIES TO:
MongoDB
This article shows you how to connect to Azure Cosmos DB for MongoDB using the native MongoDB npm package. Once connected, you can perform operations on databases, collections, and docs.
Note
The example code snippets are available on GitHub as a JavaScript project.
API for MongoDB reference documentation | MongoDB Package (npm)
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
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
To run the app, use a terminal to navigate to the application directory and run the application.
node index.js
To connect with the MongoDB native driver to Azure Cosmos DB, create an instance of the MongoClient
class. This class is the starting point to perform all operations against databases.
The most common constructor for MongoClient has two parameters:
Parameter | Example value | Description |
---|---|---|
url |
COSMOS_CONNECTION_STRING environment variable |
API for MongoDB connection string to use for all requests |
options |
{ssl: true, tls: true, } |
MongoDB Options for the connection. |
Refer to the Troubleshooting guide for connection issues.
Create a shell variable for resourceGroupName.
# Variable for resource group name
resourceGroupName="msdocs-cosmos"
Use the az cosmosdb list
command to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.
# Retrieve most recently created account name
accountName=$(
az cosmosdb list \
--resource-group $resourceGroupName \
--query "[0].name" \
--output tsv
)
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
Record the PRIMARY KEY values. You'll use these credentials later.
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:
export COSMOS_CONNECTION_STRING="<cosmos-connection-string>"
Add dependencies to reference the MongoDB and DotEnv npm packages.
// Read .env file and set environment variables
require('dotenv').config();
// Use official mongodb driver to connect to the server
const { MongoClient } = require('mongodb');
Define a new instance of the MongoClient
class using the constructor, and process.env.
to use the connection string.
// New instance of MongoClient with connection string
// for Cosmos DB
const url = process.env.COSMOS_CONNECTION_STRING;
const client = new MongoClient(url);
// connect to the server
await client.connect();
// client options
const options = client.options
console.log(`Options:\n${Object.keys(options).map(key => `\t${key}: ${options[key]}\n`)}`);
For more information on different ways to create a MongoClient
instance, see MongoDB NodeJS Driver Quick Start.
When your application is finished with the connection, remember to close it. The .close()
call should be after all database calls are made.
client.close()
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.
Hierarchical diagram showing an Azure Cosmos DB for MongoDB account at the top. The account has two child database nodes. One of the database nodes includes two child collection nodes. The other database node includes a single child collection node. That single collection node has three child doc nodes.
Each type of resource is represented by one or more associated JavaScript classes. Here's a list of the most common classes:
Class | Description |
---|---|
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. |
The following guides show you how to use each of these classes to build your application.
Guide:
Now that you've connected to an API for MongoDB account, use the next guide to create and manage databases.
Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
Introducción a MongoDB API en Azure Cosmos DB - Training
Obtenga información sobre los conceptos básicos de Azure Cosmos DB for MongoDB.
Certification
Microsoft Certified: Azure Cosmos DB Developer Specialty - Certifications
Escribe consultas eficaces, crea directivas de indexación, administra y aprovisiona recursos en la API de SQL y el SDK con Microsoft Azure Cosmos DB.
Documentation
Inicio rápido: Node.js - Azure Cosmos DB for MongoDB (RU)
Implemente una aplicación web de .NET que use la biblioteca cliente para Node.js para interactuar con los datos de Azure Cosmos DB para MongoDB (RU) en este inicio rápido.
Uso de la API de Azure Cosmos DB para MongoDB para compilar una aplicación de Node.js
Tutorial que crea una base de datos en línea mediante la API de Azure Cosmos DB para MongoDB.
Consulta de los datos con Azure Cosmos DB for MongoDB
Obtenga información sobre cómo consultar datos de Azure Cosmos DB for MongoDB mediante comandos de shell de MongoDB.