Bird
Raised Fist0
Azurecloud~5 mins

Functions with Cosmos DB integration in Azure - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main benefit of using Azure Functions with Cosmos DB integration?
easy
A. Automatically run code when data changes in Cosmos DB
B. Manually trigger code only through HTTP requests
C. Store large files directly in Cosmos DB
D. Replace Cosmos DB with Azure Blob Storage

Solution

  1. Step 1: Understand Azure Functions with Cosmos DB

    Azure Functions can be triggered automatically by changes in Cosmos DB data.
  2. Step 2: Identify the main benefit

    This automatic trigger saves resources by running code only when needed, without manual calls.
  3. Final Answer:

    Automatically run code when data changes in Cosmos DB -> Option A
  4. Quick Check:

    Functions trigger on data changes = A [OK]
Hint: Functions run on data change events automatically [OK]
Common Mistakes:
  • Thinking functions run only on HTTP triggers
  • Confusing Cosmos DB with file storage
  • Assuming manual triggers are required
2. Which of the following is the correct binding direction for a Cosmos DB input binding in an Azure Function?
easy
A. direction: "out"
B. direction: "both"
C. direction: "trigger"
D. direction: "in"

Solution

  1. Step 1: Recall binding directions

    Input bindings receive data into the function, so their direction is "in".
  2. Step 2: Match binding direction for Cosmos DB input

    Cosmos DB input binding must have direction set to "in" to read data.
  3. Final Answer:

    direction: "in" -> Option D
  4. Quick Check:

    Input binding direction = in [OK]
Hint: Input bindings always use direction "in" [OK]
Common Mistakes:
  • Using "out" for input bindings
  • Confusing trigger with input binding
  • Using invalid directions like "both"
3. Given this Azure Function code snippet triggered by Cosmos DB changes, what will be logged if a new document with id "123" is added?
module.exports = async function (context, documents) {
  if (!!documents && documents.length > 0) {
    context.log(`Document id: ${documents[0].id}`);
  }
};
medium
A. No output logged
B. Document id: undefined
C. Document id: 123
D. Error: documents is not defined

Solution

  1. Step 1: Understand the trigger input

    The function receives an array 'documents' with changed documents; the first document has id "123".
  2. Step 2: Analyze the logging statement

    The code logs the id of the first document, which is "123".
  3. Final Answer:

    Document id: 123 -> Option C
  4. Quick Check:

    documents[0].id = 123 logged [OK]
Hint: documents array holds changed items; access first with documents[0] [OK]
Common Mistakes:
  • Assuming documents is undefined
  • Logging without checking documents length
  • Confusing document id property
4. You wrote an Azure Function triggered by Cosmos DB changes, but it never runs when documents change. Which is the most likely cause?
medium
A. The function code has a syntax error
B. The function.json binding has incorrect connection string name
C. The Cosmos DB container is empty
D. The function app is stopped

Solution

  1. Step 1: Check trigger configuration

    If the connection string name in function.json is wrong, the function won't connect to Cosmos DB changes.
  2. Step 2: Consider other causes

    Syntax errors cause failures but usually show errors; empty container still triggers on inserts; stopped app won't run but question implies function exists.
  3. Final Answer:

    The function.json binding has incorrect connection string name -> Option B
  4. Quick Check:

    Wrong connection string stops trigger [OK]
Hint: Check connection string name in function.json first [OK]
Common Mistakes:
  • Ignoring binding configuration errors
  • Assuming empty container prevents triggers
  • Not verifying function app status
5. You want to create an Azure Function that writes a summary document to Cosmos DB whenever multiple documents are added. Which binding setup should you use?
hard
A. Use Cosmos DB trigger for input and Cosmos DB output binding for summary document
B. Use HTTP trigger and Cosmos DB input binding only
C. Use Cosmos DB input binding only, no trigger
D. Use Timer trigger and Cosmos DB output binding only

Solution

  1. Step 1: Identify trigger for reacting to data changes

    Cosmos DB trigger runs the function automatically when documents change.
  2. Step 2: Use output binding to write summary

    Output binding lets the function write a new summary document back to Cosmos DB.
  3. Final Answer:

    Use Cosmos DB trigger for input and Cosmos DB output binding for summary document -> Option A
  4. Quick Check:

    Trigger input + output binding for writing = C [OK]
Hint: Trigger on changes, output binding to write summary [OK]
Common Mistakes:
  • Using HTTP trigger instead of Cosmos DB trigger
  • Missing output binding for writing data
  • Using timer trigger without data event