0
0
Azurecloud~5 mins

Functions with Cosmos DB integration in Azure - Commands & Configuration

Choose your learning style9 modes available
Introduction
Azure Functions lets you run small pieces of code in the cloud without managing servers. Integrating with Cosmos DB allows your function to automatically read or write data when triggered, making your app reactive and scalable.
When you want to automatically process data changes in a Cosmos DB collection without polling.
When you need to create a serverless API that reads or writes data to Cosmos DB on demand.
When you want to trigger workflows based on new documents added to Cosmos DB.
When you want to keep your app responsive by offloading database operations to background functions.
When you want to build event-driven apps that react to database updates in real time.
Config File - function.json
function.json
{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "inputDocuments",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "CosmosDBConnection",
      "databaseName": "example-db",
      "collectionName": "items",
      "createLeaseCollectionIfNotExists": true
    }
  ]
}

This file configures the Azure Function trigger.

  • type: Defines this function triggers on Cosmos DB changes.
  • name: The variable name in your code for incoming documents.
  • leaseCollectionName: Tracks processed changes to avoid duplicates.
  • connectionStringSetting: The app setting name holding Cosmos DB connection info.
  • databaseName and collectionName: Specify which Cosmos DB data to watch.
  • createLeaseCollectionIfNotExists: Automatically creates lease collection if missing.
Commands
Initialize a new Azure Functions project using the .NET runtime to prepare for adding your function.
Terminal
func init MyFunctionApp --worker-runtime dotnet
Expected OutputExpected
Writing C# project file... Restore completed in 1.23 sec for C:\MyFunctionApp\MyFunctionApp.csproj.
--worker-runtime - Specifies the language runtime for the function app.
Create a new function triggered by Cosmos DB changes using the built-in template.
Terminal
func new --name CosmosDBTriggerFunction --template "Azure Cosmos DB trigger"
Expected OutputExpected
Created new C# function 'CosmosDBTriggerFunction' in project.
--name - Names the new function.
--template - Selects the function trigger template.
Run the function app locally to test the Cosmos DB trigger and see logs when data changes.
Terminal
func start
Expected OutputExpected
Hosting environment: Production Content root path: C:\MyFunctionApp Now listening on: http://localhost:7071 Application started. Press Ctrl+C to shut down. [Information] Executing 'CosmosDBTriggerFunction' (Reason='New documents in Cosmos DB', Id=12345)
Create a new Azure Function app in the cloud with .NET runtime and link it to a storage account.
Terminal
az functionapp create --resource-group example-rg --consumption-plan-location eastus --runtime dotnet --functions-version 4 --name example-func-app --storage-account examplestorageacct
Expected OutputExpected
{ "id": "/subscriptions/xxxx/resourceGroups/example-rg/providers/Microsoft.Web/sites/example-func-app", "location": "eastus", "name": "example-func-app", "type": "Microsoft.Web/sites" }
--resource-group - Specifies the Azure resource group.
--consumption-plan-location - Sets the region and plan type for serverless billing.
--runtime - Sets the function runtime language.
--functions-version - Specifies the Azure Functions runtime version.
Set the Cosmos DB connection string in the function app settings so the function can access the database.
Terminal
az functionapp config appsettings set --name example-func-app --resource-group example-rg --settings CosmosDBConnection="AccountEndpoint=https://example-cosmos.documents.azure.com:443/;AccountKey=YOUR_ACCOUNT_KEY;"
Expected OutputExpected
{"id":"/subscriptions/xxxx/resourceGroups/example-rg/providers/Microsoft.Web/sites/example-func-app/config/appsettings","name":"appsettings","properties":{"CosmosDBConnection":"AccountEndpoint=https://example-cosmos.documents.azure.com:443/;AccountKey=YOUR_ACCOUNT_KEY;"}}
--settings - Defines key-value pairs for app configuration.
Key Concept

If you remember nothing else from this pattern, remember: Azure Functions can automatically react to Cosmos DB data changes by using a trigger binding configured with a connection string and monitored collection.

Common Mistakes
Not setting the CosmosDBConnection app setting with the correct connection string.
The function cannot connect to Cosmos DB and will fail to trigger.
Use the Azure CLI or portal to set the CosmosDBConnection app setting with the full connection string.
Forgetting to create or specify the lease collection in the function.json binding.
The function cannot track processed changes and may process the same documents multiple times.
Set leaseCollectionName and createLeaseCollectionIfNotExists to true in function.json.
Running the function app without starting the Cosmos DB emulator or having access to the real Cosmos DB account.
The function will not receive any trigger events and appears idle.
Ensure Cosmos DB emulator is running locally or the function app has network access to the Cosmos DB account.
Summary
Initialize an Azure Functions project with the .NET runtime.
Create a Cosmos DB trigger function using the Azure Functions template.
Configure function.json to specify the Cosmos DB collection and lease collection.
Run the function locally to test triggers from Cosmos DB changes.
Deploy the function app to Azure and set the Cosmos DB connection string in app settings.