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)
Top Articles
IT-Helpdesk vs. IT-Servicedesk: Der Unterschied im IT-Support
Was ist ein IT-Help Desk: Ein Leitfaden für 2023
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated:

Views: 6458

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.