Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In this quickstart, you create a basic Azure DocumentDB application using Node.js. Azure DocumentDB is a NoSQL data store that allows applications to store documents in the cloud and access them using official MongoDB drivers. This guide shows how to create documents and perform basic tasks in your Azure DocumentDB cluster using Node.js.
API reference | Source code | Package (npm)
Prerequisites
An Azure subscription
- If you don't have an Azure subscription, create a free account
- Node.js 22 or newer
Create an Azure DocumentDB cluster
To get started, you first need to create an Azure DocumentDB cluster, which serves as the foundation for storing and managing your NoSQL data.
Sign in to the Azure portal (https://portal.azure.com).
From the Azure portal menu or the Home page, select Create a resource.
On the New page, search for and select Azure DocumentDB.
On the Create Azure DocumentDB cluster page and within the Basics section, select the Configure option within the Cluster tier section.
On the Scale page, configure these options and then select Save to persist your changes to the cluster tier.
Value Cluster tier M30 tier, 2 vCore, 8-GiB RAMStorage per shard 128 GiB
Back in the Basics section, configure the following options:
Value Subscription Select your Azure subscription Resource group Create a new resource group or select an existing resource group Cluster name Provide a globally unique name Location Select a supported Azure region for your subscription MongoDB version Select 8.0Admin username Create a username to access the cluster as a user administrator Password Use a unique password associated with the username
Tip
Record the values you use for username and password. These values are used later in this guide. For more information about valid values, see cluster limitations.
Select Next: Networking.
In the Firewall rules section on the Networking tab, configure these options:
Value Connectivity method Public accessAllow public access from Azure services and resources within Azure to this cluster Enabled Add a firewall rule for your current client device to grant access to the cluster by selecting + Add current client IP address.
Tip
In many corporate environments, developer machine IP addresses are hidden due to a VPN or other corporate network settings. In these cases, you can temporarily allow access to all IP addresses by adding the
0.0.0.0-255.255.255.255IP address range as a firewall rule. Use this firewall rule only temporarily as a part of connection testing and development.Select Review + create.
Review the settings you provide, and then select Create. It takes a few minutes to create the cluster. Wait for the resource deployment is complete.
Finally, select Go to resource to navigate to the Azure DocumentDB cluster in the portal.
Get cluster credentials
Get the credentials you use to connect to the cluster.
On the cluster page, select the Connection strings option in the resource menu.
In the Connection strings section, copy or record the value from the Connection string field.
Important
The connection string in the portal doesn't include the password value. You must replace the <password> placeholder with the credentials you entered when you created the cluster or enter the password interactively.
Initialize the project
Create a new Node.js project in your current directory.
Start in an empty directory.
Open a terminal in the current directory.
Initialize a Node.js project.
npm init -yInstall TypeScript and initialize TypeScript configuration (optional for TypeScript support).
npm install -D typescript @types/node npx tsc --init
Install the client library
The client library is available through npm, as the mongodb package.
Install the MongoDB Node.js driver using npm.
npm install mongodbOpen and review the package.json file to validate that the package entry exists.
Import the required modules into your application code:
import { MongoClient, Db, Collection, Document } from 'mongodb';const { MongoClient } = require('mongodb');
Object model
| Name | Description |
|---|---|
MongoClient |
Type used to connect to MongoDB. |
Db |
Represents a database in the cluster. |
Collection<Document> |
Represents a collection within a database in the cluster. |
Code examples
The code in this application connects to a database named adventureworks and a collection named products. The products collection contains details such as name, category, quantity, a unique identifier, and a sale flag for each product. The code samples here perform the most common operations when working with a collection.
Authenticate the client
First, connect to the client using a basic connection string.
Create the main function and set up the connection string. Replace
<your-cluster-name>,<your-username>, and<your-password>with your actual cluster information.async function main(): Promise<void> { // Connection string for Azure DocumentDB cluster const connectionString = "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"; // Create a new client and connect to the server const client = new MongoClient(connectionString);async function main() { // Connection string for Azure DocumentDB cluster const connectionString = "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"; // Create a new client and connect to the server const client = new MongoClient(connectionString);Connect to the MongoDB client and verify the connection.
try { // Connect to the MongoDB cluster await client.connect(); // Ping the server to verify connection await client.db("admin").command({ ping: 1 }); console.log("Successfully connected and pinged Azure DocumentDB");try { // Connect to the MongoDB cluster await client.connect(); // Ping the server to verify connection await client.db("admin").command({ ping: 1 }); console.log("Successfully connected and pinged Azure DocumentDB");
Get a collection
Now, get your database and collection. If the database and collection doesn't already exist, use the driver to create it for you automatically.
Get a reference to the database.
// Get database reference const database: Db = client.db("adventureworks"); console.log(`Connected to database: ${database.databaseName}`);// Get database reference const database = client.db("adventureworks"); console.log(`Connected to database: ${database.databaseName}`);Get a reference to the collection within the database.
// Get collection reference const collection: Collection<Document> = database.collection("products"); console.log("Connected to collection: products");// Get collection reference const collection = database.collection("products"); console.log("Connected to collection: products");
Create a document
Then, create a couple of new documents within your collection. Upsert the documents to ensure that it replaces any existing documents if they already exist with the same unique identifier.
Create sample product documents.
// Create sample products interface Product { _id: string; name: string; category: string; quantity: number; price: number; sale: boolean; } const products: Product[] = [ { _id: "00000000-0000-0000-0000-000000004018", name: "Windry Mittens", category: "apparel-accessories-gloves-and-mittens", quantity: 121, price: 35.00, sale: false, }, { _id: "00000000-0000-0000-0000-000000004318", name: "Niborio Tent", category: "gear-camp-tents", quantity: 140, price: 420.00, sale: true, } ];// Create sample products const products = [ { _id: "00000000-0000-0000-0000-000000004018", name: "Windry Mittens", category: "apparel-accessories-gloves-and-mittens", quantity: 121, price: 35.00, sale: false, }, { _id: "00000000-0000-0000-0000-000000004318", name: "Niborio Tent", category: "gear-camp-tents", quantity: 140, price: 420.00, sale: true, } ];Insert the documents using upsert operations.
// Insert documents with upsert for (const product of products) { const filter = { _id: product._id }; const options = { upsert: true }; await collection.replaceOne(filter, product, options); console.log(`Upserted product: ${product.name}`); }// Insert documents with upsert for (const product of products) { const filter = { _id: product._id }; const options = { upsert: true }; await collection.replaceOne(filter, product, options); console.log(`Upserted product: ${product.name}`); }
Retrieve a document
Next, perform a point read operation to retrieve a specific document from your collection.
Define the filter to find a specific document by ID.
// Retrieve a specific document by ID const filter = { _id: "00000000-0000-0000-0000-000000004018" };// Retrieve a specific document by ID const filter = { _id: "00000000-0000-0000-0000-000000004018" };Execute the query and retrieve the result.
const retrievedProduct = await collection.findOne(filter); if (retrievedProduct) { console.log(`Retrieved product: ${retrievedProduct.name} - $${retrievedProduct.price}`); } else { console.log("Product not found"); }const retrievedProduct = await collection.findOne(filter); if (retrievedProduct) { console.log(`Retrieved product: ${retrievedProduct.name} - $${retrievedProduct.price}`); } else { console.log("Product not found"); }
Query documents
Finally, query multiple documents using the MongoDB Query Language (MQL).
Define a query to find documents matching specific criteria.
// Query for products on sale const saleFilter = { sale: true }; const saleProducts = await collection.find(saleFilter).toArray();// Query for products on sale const saleFilter = { sale: true }; const saleProducts = await collection.find(saleFilter).toArray();Iterate through the results to display the matching documents.
console.log("Products on sale:"); for (const product of saleProducts) { console.log(`- ${product.name}: $${product.price.toFixed(2)} (Category: ${product.category})`); } } catch (error) { console.error("An error occurred:", error); } finally { await client.close(); } } main().catch(console.error);console.log("Products on sale:"); for (const product of saleProducts) { console.log(`- ${product.name}: $${product.price.toFixed(2)} (Category: ${product.category})`); } } catch (error) { console.error("An error occurred:", error); } finally { await client.close(); } } main().catch(console.error);
Explore your data using Visual Studio Code
Use the DocumentDB extension in Visual Studio Code to perform core database operations, including querying, inserting, updating, and deleting data.
Open Visual Studio Code.
Navigate to the Extensions view and search for the term
DocumentDB. Locate the DocumentDB for VS Code extension.Select the Install button for the extension. Wait for the installation to complete. Reload Visual Studio Code if prompted.
Navigate to the DocumentDB extension by selecting the corresponding icon in the Activity Bar.
In the DocumentDB Connections pane, select + New Connection....
In the dialog, select Service Discovery and then Azure DocumentDB - Azure Service Discovery.
Select your Azure subscription and your newly created Azure DocumentDB cluster.
Tip
In many corporate environments, developer machine IP addresses are hidden due to a VPN or other corporate network settings. In these cases, you can temporarily allow access to all IP addresses by adding the
0.0.0.0-255.255.255.255IP address range as a firewall rule. Use this firewall rule only temporarily as a part of connection testing and development. For more information, see configure firewall.Back in the DocumentDB Connections pane, expand the node for your cluster and navigate to your existing document and collection nodes.
Open the context menu for the collection and then select DocumentDB Scrapbook > New DocumentDB Scrapbook.
Enter the following MongoDB Query Language (MQL) commands and then select Run All. Observe the output from the commands.
db.products.find({ price: { $gt: 200 }, sale: true }) .sort({ price: -1 }) .limit(3)
Clean up resources
When you're done with the Azure DocumentDB cluster, you can delete the Azure resources you created so you don't incur more charges.
In the Azure portal search bar, search for and select Resource groups.
In the list, select the resource group you used for this quickstart.
On the resource group page, select Delete resource group.
In the deletion confirmation dialog, enter the name of the resource group to confirm that you intend to delete it. Finally, select Delete to permanently delete the resource group.