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


Get started with MongoDB 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.


The example code snippets are available on GitHub as a .NET project.

API for MongoDB reference documentation | MongoDB Package (NuGet)


Prerequisite check

  • In a terminal or command window, run dotnet --list-sdks to check that .NET 6.x is one of the available versions.
  • Run az --version (Azure CLI) or Get-Module -ListAvailable AzureRM (Azure PowerShell) to check that you have the appropriate Azure command-line tools installed.

Setting up

This section walks you through creating an Azure Cosmos DB account and setting up a project that uses the MongoDB NuGet packages.

Create an Azure Cosmos DB account

This quickstart will create a single Azure Cosmos DB account using the API for MongoDB.

  1. Create shell variables for accountName, resourceGroupName, and location.

    # Variable for resource group name
    # Variable for account name with a randomnly generated suffix
    let suffix=$RANDOM*$RANDOM
  2. If you haven't already, sign in to the Azure CLI using the az login command.

  3. Use the az group create command to create a new resource group in your subscription.

    az group create \
        --name $resourceGroupName \
        --location $location
  4. Use the az cosmosdb create command to create a new Azure Cosmos DB for MongoDB account with default settings.

    az cosmosdb create \
        --resource-group $resourceGroupName \
        --name $accountName \
        --locations regionName=$location
        --kind MongoDB

Get MongoDB connection string

  1. Find the API for MongoDB connection string from the list of connection strings for the account with the az cosmosdb keys list command.

    az cosmosdb keys list --type connection-strings \
        --resource-group $resourceGroupName \
        --name $accountName 
  2. Record the PRIMARY KEY values. You'll use these credentials later.

Create a new .NET app

Create a new .NET application in an empty folder using your preferred terminal. Use the dotnet new console to create a new console app.

dotnet new console -o <app-name>

Install the NuGet package

Add the MongoDB.Driver NuGet package to the new .NET project. Use the dotnet add package command specifying the name of the NuGet package.

dotnet add package MongoDb.Driver

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:

$env:COSMOS_CONNECTION_STRING = "<cosmos-connection-string>"

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 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.

You'll 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 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.
  • Collection - 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.

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 you set 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 will return 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 will create 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(
    "Yamba Surfboard", 

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:");

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(
    "Sand Surfboard",

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

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

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 steps it has performed.

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 NoSQL account, you can delete the corresponding resource group.

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

az group delete --name $resourceGroupName