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 deploy a basic Azure Cosmos DB for MongoDB vCore application using .NET. Azure Cosmos DB for MongoDB vCore is a schemaless data store allowing applications to store unstructured documents in the cloud with MongoDB libraries. You learn how to create documents and perform basic tasks within your Azure Cosmos DB resource using .NET.
Library source code | Package (NuGet) | Azure Developer CLI
Azure Developer CLI
Docker Desktop
An Azure subscription
- If you don't have an Azure subscription, create a Trial before you begin.
- .NET SDK 9.0
Use the Azure Developer CLI (azd
) to create an Azure Cosmos DB for MongoDB vCore cluster and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.
Open a terminal in an empty directory.
If you're not already authenticated, 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
Use
azd init
to initialize the project.azd init --template cosmos-db-mongodb-vcore-dotnet-quickstart
During initialization, configure a unique environment name.
Deploy the cluster using
azd up
. The Bicep templates also deploy a sample web application.azd up
During the provisioning process, select your subscription, desired location, and target resource group. Wait for the provisioning process to complete. The process can take approximately five minutes.
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.
Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.
The client library is available through NuGet, as the MongoDB.Driver
package. For Microsoft Entra authentication, use the Azure.Identity
package from the Azure SDK for .NET.
Open a terminal and navigate to the
/src/web
folder.cd ./src/web
If not already installed, install the
MongoDB.Driver
package usingdotnet add package
.dotnet add package MongoDB.Driver
If not already installed, install the
Azure.Identity
package.dotnet add package Azure.Identity
Open and review the src/api/Microsoft.Learn.AzureCosmosDBMongoDBQuickstart.Api.csproj file to validate that both package entries exist.
Import the following namespaces into your application code:
Package | Source | |
---|---|---|
Azure.Core |
Azure.Identity |
Azure SDK for .NET |
Azure.Identity |
Azure.Identity |
Azure SDK for .NET |
MongoDB.Driver |
MongoDB.Driver |
Official MongoDB driver for .NET |
MongoDB.Driver.Authentication.Oidc |
MongoDB.Driver |
Official MongoDB driver for .NET |
using Azure.Core;
using Azure.Identity;
using MongoDB.Driver;
using MongoDB.Driver.Authentication.Oidc;
Name | Description |
---|---|
MongoClient |
Type used to connect to MongoDB. |
Database |
Represents a database on the cluster. |
Collection |
Represents a collection within a database on the cluster. |
- Authenticate the client
- Get a database
- Get a collection
- Create a document
- Get a document
- Query documents
- Delete a document
The sample code in the template uses a database named cosmicworks
and collection named products
. The products
collection contains details such as name, category, quantity, and a unique identifier for each product. The collection uses the /category
property as a shard key.
While Microsoft Entra authentication for Azure Cosmos DB for MongoDB vCore can use well known TokenCredential
types, you must implement a custom token handler. This sample implementation can be used to create a MongoClient
with support for standard Microsoft Entra authentication of many identity types.
First, create a new class in a separate file that implements
IOidcCallback
interface.using Azure.Core; using MongoDB.Driver.Authentication.Oidc; internal sealed class AzureIdentityTokenHandler( TokenCredential credential, string tenantId ) : IOidcCallback { private readonly string[] scopes = ["https://ossrdbms-aad.database.chinacloudapi.cn/.default"]; public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = credential.GetToken( new TokenRequestContext(scopes, tenantId: tenantId), cancellationToken ); return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow); } public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = await credential.GetTokenAsync( new TokenRequestContext(scopes, parentRequestId: null, tenantId: tenantId), cancellationToken ); return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow); } }
Create a new instance of your custom handler class passing in a new instance of the
DefaultAzureCredential
type and your tenant ID.DefaultAzureCredential credential = new(); string tenantId = "<microsoft-entra-tenant-id>"; AzureIdentityTokenHandler tokenHandler = new(credential, tenantId);
Build an instance of
MongoUrl
using the endpoint and scheme for your recently deployed Azure Cosmos DB for MongoDB vCore instance.string clusterName = "<azure-cosmos-db-mongodb-vcore-cluster-name>"; MongoUrl url = MongoUrl.Create($"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/");
Configure your
MongoClient
instance using known best practice configuration options for Azure Cosmos DB for MongoDB vCore and the customIOidcCallback
implementation.MongoClientSettings settings = MongoClientSettings.FromUrl(url); settings.UseTls = true; settings.RetryWrites = false; settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2); settings.Credential = MongoCredential.CreateOidcCredential(tokenHandler); settings.Freeze(); MongoClient client = new(settings);
This sample creates an instance of the IMongoDatabase
interface using the GetDatabase
method of the MongoClient
class.
IMongoDatabase database = client.GetDatabase("<database-name>");
This sample creates an instance of the generic IMongoCollection<>
interface using the GetCollection<>
generic method of the IMongoDatabase
interface. The generic interface and method both uses a type named Product
defined in another class.
IMongoCollection<Product> collection = database.GetCollection<Product>("<collection-name>");
public record Product(
string id,
string category,
string name,
int quantity,
decimal price,
bool clearance
);
Create a document in the collection using collection.ReplaceOneAsync<>
with the generic Product
type parameter. This method "upserts" the document effectively replacing it if it already exists in the collection.
Product document = new(
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
category: "gear-surf-surfboards",
name: "Yamba Surfboard",
quantity: 12,
price: 850.00m,
clearance: false
);
await collection.ReplaceOneAsync<Product>(
doc => doc.id == document.id,
document,
new ReplaceOptions { IsUpsert = true }
);
Perform a read operation by using both the unique identifier (id
) for the documents. Use collection.FindAsync<>
with the generic Product
type parameter to efficiently retrieve the specific document.
Product? document = await collection.Find(
doc => doc.id == "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
).SingleOrDefaultAsync();
Perform a query over multiple documents in a container using collection.AsQueryable()
and language-integrated query (LINQ). This query finds all documents within a specified category (shard key).
List<Product> documents = await collection.Find(
filter: doc => doc.category == "gear-surf-surfboards"
).ToListAsync();
foreach (Product document in documents)
{
// Do something with each document
}
Delete a document by sending a filter for the unique identifier of the document. Use collection.DeleteOneAsync<>
to asynchronously remove the document from the collection.
await collection.DeleteOneAsync(
doc => doc.id == "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
);
Use the Visual Studio Code extension for Azure Cosmos DB to explore your MongoDB vCore data. You can perform core database operations including, but not limited to:
- Performing queries using a scrapbook or the query editor
- Modifying, updating, creating, and deleting documents
- Importing bulk data from other sources
- Managing databases and collections
For more information, see How-to use Visual Studio Code extension to explore Azure Cosmos DB for MongoDB vCore data.
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
azd down --force