Get started with Azure Cosmos DB for MongoDB using JavaScript
Članek
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.
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.
Console
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.
Console
npm install mongodb dotenv
To run the app, use a terminal to navigate to the application directory and run the application.
Console
node index.js
Connect with MongoDB native driver to Azure Cosmos DB for MongoDB
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
# 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.
Azure CLI
# Retrieve most recently created account nameaccountName=$(
az cosmosdb list \
--resource-group$resourceGroupName \
--query"[0].name" \
--output tsv
)
Create a shell variable for RESOURCE_GROUP_NAME.
Azure PowerShell
# Variable for resource group name$RESOURCE_GROUP_NAME = "msdocs-cosmos"
Use the Get-AzCosmosDBAccountKey cmdlet to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.
Azure PowerShell
# Get the name of the first Azure Cosmos DB account in your resource group$ACCOUNT_NAME = (Get-AzCosmosDBAccount -ResourceGroupName$RESOURCE_GROUP_NAME)[0].Name
Skip this step and use the information for the portal in the next step.
Navigate to the existing Azure Cosmos DB for MongoDB account page.
From the Azure Cosmos DB for MongoDB account page, select the Connection String navigation menu option.
Record the value for the PRIMARY CONNECTION STRING field. You use this value in a later step.
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:
A .env file is a standard way to store environment variables in a project. Create a .env file in the root of your project. Add the following lines to the .env file:
Add dependencies to reference the MongoDB and DotEnv npm packages.
JavaScript
// Read .env file and set environment variablesrequire('dotenv').config();
// Use official mongodb driver to connect to the serverconst { MongoClient } = require('mongodb');
Define a new instance of the MongoClient class using the constructor, and process.env. to use the connection string.
JavaScript
// New instance of MongoClient with connection string// for Cosmos DBconst url = process.env.COSMOS_CONNECTION_STRING;
const client = new MongoClient(url);
// connect to the serverawait client.connect();
// client optionsconst options = client.options
console.log(`Options:\n${Object.keys(options).map(key => `\t${key}: ${options[key]}\n`)}`);
When your application is finished with the connection, remember to close it. The .close() call should be after all database calls are made.
JavaScript
client.close()
Use MongoDB client classes with Azure Cosmos DB for API for MongoDB
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:
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.
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.
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.
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.
Azure Cosmos DB for MongoDB facilita el uso de Azure Cosmos DB como si fuera una base de datos de MongoDB. Para aplicar su experiencia en MongoDB y seguir usando sus controladores, SDK y herramientas favoritos de MongoDB, apunte la aplicación a la cadena de conexión de la cuenta de la API para MongoDB.
Implemente una aplicación web de .NET que use la biblioteca cliente para .NET para interactuar con los datos de Azure Cosmos DB para MongoDB (RU) en este inicio rápido.