Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (2024)

  • Article

APPLIES TO:Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (1)MongoDB

  • Node.js
  • Python
  • Java
  • .NET
  • Golang

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

  • An Azure account with an active subscription. Create an account for free.
  • GitHub account
  • An Azure account with an active subscription. Create an account for free.
  • Azure Developer CLI
  • Docker Desktop

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.

Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (2)

Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (3)

  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.

    Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (4)

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.

Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (5)

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

  • Authenticate the client
  • Get database instance
  • Get collection instance
  • Use chained methods
  • Create an index
  • Create a doc
  • Get an doc
  • Run queries

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 variablesrequire('dotenv').config();const random = Math.floor(Math.random() * 100);// Use official mongodb driver to connect to the serverconst { 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 DBconst 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 serverawait client.connect();

Get database instance

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

// Database reference with creation if it does not already existconst 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 existconst 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 nameconst 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 collectionconst 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 directlyconst upsertResult1 = await collection.updateOne(query, update, options);console.log(`upsertResult1: ${JSON.stringify(upsertResult1)}\n`);// Update via upsert on chained instanceconst 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 categoryconst allProductsQuery = { category: "gear-surf-surfboards" };// get all documents, sorted by name, convert cursor into arrayconst 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: adventureworksNew collection: productsupsertResult1: {"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.

  • Azure CLI
  • PowerShell
  • Portal

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.

Migrate MongoDB to Azure Cosmos DB for MongoDB offline

Quickstart - Azure Cosmos DB for MongoDB driver for MongoDB (2024)

References

Top Articles
Devil May Cry 3: Dante's Awakening walkthrough/M04
Secret Missions - Devil May Cry 5 Guide - IGN
Golden Abyss - Chapter 5 - Lunar_Angel
1970 Chevrolet Chevelle SS - Skyway Classics
Needle Nose Peterbilt For Sale Craigslist
Midway Antique Mall Consignor Access
Bbc 5Live Schedule
Things To Do In Atlanta Tomorrow Night
Turning the System On or Off
How Much Is Tj Maxx Starting Pay
Tracking Your Shipments with Maher Terminal
Craigslist Edmond Oklahoma
Directions To 401 East Chestnut Street Louisville Kentucky
Illinois Gun Shows 2022
Nashville Predators Wiki
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Free Online Games on CrazyGames | Play Now!
Betaalbaar naar The Big Apple: 9 x tips voor New York City
LCS Saturday: Both Phillies and Astros one game from World Series
Wnem Tv5 Obituaries
Living Shard Calamity
Craigslist Wilkes Barre Pa Pets
Discord Nuker Bot Invite
Cable Cove Whale Watching
Redbox Walmart Near Me
+18886727547
Broken Gphone X Tarkov
Citibank Branch Locations In Orlando Florida
Fedex Walgreens Pickup Times
Edict Of Force Poe
Acadis Portal Missouri
Boggle BrainBusters: Find 7 States | BOOMER Magazine
Case Funeral Home Obituaries
The disadvantages of patient portals
8 Ball Pool Unblocked Cool Math Games
Dee Dee Blanchard Crime Scene Photos
Sukihana Backshots
Jack In The Box Menu 2022
Who Is Responsible for Writing Obituaries After Death? | Pottstown Funeral Home & Crematory
Nail Salon Open On Monday Near Me
Sofia With An F Mugshot
COVID-19/Coronavirus Assistance Programs | FindHelp.org
How Big Is 776 000 Acres On A Map
Mynord
M&T Bank
Dobratz Hantge Funeral Chapel Obituaries
UNC Charlotte Admission Requirements
Shannon Sharpe Pointing Gif
Chitterlings (Chitlins)
Gainswave Review Forum
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 6164

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.