Editja

Ixxerja permezz ta’


Quickstart: Azure Cosmos DB for MongoDB for .NET with the MongoDB driver

APPLIES TO: MongoDB

Get started with MongoDB to create databases, collections, and docs within your Azure Cosmos DB resource. Follow these steps to deploy a minimal solution to your environment using the Azure Developer CLI.

API for MongoDB reference documentation | MongoDB Package (NuGet) packages/Microsoft.Azure.Cosmos) | Azure Developer CLI

Prerequisites

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.

Open in GitHub Codespaces

Open in Dev Container

Important

GitHub accounts include an entitlement of storage and core hours at no cost. For more information, see included storage and core hours for GitHub accounts.

  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-dotnet-quickstart
    

    Note

    This quickstart uses the azure-samples/cosmos-db-mongodb-dotnet-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.

    Screenshot of the running web application.


Install the client library

The client library is available through NuGet, as the Microsoft.Azure.Cosmos package.

  1. Open a terminal and navigate to the /src/web folder.

    cd ./src/web
    
  2. If not already installed, install the MongoDb.Driver package using dotnet add package.

    dotnet add package MongoDb.Driver
    
  3. Also, install the Azure.Identity package if not already installed.

    dotnet add package Azure.Identity
    

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.

Diagram of the Azure Cosmos DB hierarchy including accounts, databases, collections, and docs.

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 shard. 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.
  • MongoDatabase - 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

The sample code demonstrated 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.

Authenticate the client

From the project directory, open the Program.cs file. In your editor, add a using directive for MongoDB.Driver.

using MongoDB.Driver;

Define a new instance of the MongoClient class using the constructor, and Environment.GetEnvironmentVariable to read the connection string set by the Azure Developer CLI earlier.

// New instance of CosmosClient class
var client = new MongoClient(Environment.GetEnvironmentVariable("MONGO_CONNECTION"));

Create a database

Use the MongoClient.GetDatabase method to create a new database if it doesn't already exist. This method returns a reference to the existing or newly created database.

// Database reference with creation if it does not already exist
var db = client.GetDatabase("adventure");

Create a collection

The MongoDatabase.GetCollection creates a new collection if it doesn't already exist and return a reference to the collection.

// Container reference with creation if it does not alredy exist
var _products = db.GetCollection<Product>("products");

Create an item

The easiest way to create a new item in a collection is to create a C# class or record type with all of the members you want to serialize into JSON. In this example, the C# record has a unique identifier, a category field for the partition key, and extra name, quantity, and sale fields.

public record Product(
    string Id,
    string Category,
    string Name,
    int Quantity,
    bool Sale
);

Create an item in the collection using the Product record by calling IMongoCollection<TDocument>.InsertOne.

// Create new object and upsert (create or replace) to container
_products.InsertOne(new Product(
    Guid.NewGuid().ToString(),
    "gear-surf-surfboards",
    "Yamba Surfboard", 
    12, 
    false
));

Get an item

In Azure Cosmos DB, you can retrieve items by composing queries using Linq. In the SDK, call IMongoCollection.FindAsync<> and pass in a C# expression to filter the results.

// Read a single item from container
var product = (await _products.FindAsync(p => p.Name.Contains("Yamba"))).FirstOrDefault();
Console.WriteLine("Single product:");
Console.WriteLine(product.Name);

Query items

After you insert an item, you can run a query to get all items that match a specific filter by treating the collection as an IQueryable. This example uses an expression to filter products by category. Once the call to AsQueryable is made, call MongoQueryable.Where to retrieve a set of filtered items.

// Read multiple items from container
_products.InsertOne(new Product(
    Guid.NewGuid().ToString(),
    "gear-surf-surfboards",
    "Sand Surfboard",
    4,
    false
));

var products = _products.AsQueryable().Where(p => p.Category == "gear-surf-surfboards");

Console.WriteLine("Multiple products:");
foreach (var prod in products)
{
    Console.WriteLine(prod.Name);
}

Run the code

This app creates an Azure Cosmos DB MongoDb API database and collection. The example then creates an item and then reads the exact same item back. Finally, the example creates a second item and then performs a query that should return multiple items. With each step, the example outputs metadata to the console about the performed steps.

To run the app, use a terminal to navigate to the application directory and run the application.

dotnet run

The output of the app should be similar to this example:

Single product name: 
Yamba Surfboard
Multiple products:
Yamba Surfboard
Sand Surfboard

Clean up resources

When you no longer need the Azure Cosmos DB for MongoDB account, you can delete the corresponding resource group.

Use the az group delete command to delete the resource group.

az group delete --name $resourceGroupName