Cosmos DB Input Bindings

Language: C# | JavaScript | Python | Java

This documentation explains how to configure and use the Cosmos DB input binding for Azure Functions. This binding allows your function to read documents from a Cosmos DB container.

Overview

The Cosmos DB input binding simplifies the process of retrieving data from your Azure Cosmos DB database. Instead of writing explicit database calls within your function code, you can declare an input binding that automatically fetches the required documents based on your configuration.

Configuration

The Cosmos DB input binding is configured in your function's function.json file. Here's a typical configuration:

{
  "bindings": [
    {
      "name": "myInputDocument",
      "type": "cosmosDBInput",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "connectionStringSetting": "CosmosDBConnectionString",
      "id": "{Query.documentId}",
      "partitionKey": "{Query.partitionKey}"
    }
  ]
}

Binding Parameters

Parameter Description Required
name The name of the variable that holds the retrieved document(s) in your function code. Yes
type Must be set to cosmosDBInput. Yes
direction Must be set to in. Yes
databaseName The name of your Cosmos DB database. Yes
collectionName The name of your Cosmos DB collection. Yes
connectionStringSetting The name of the application setting that contains your Cosmos DB connection string. Yes
id The ID of the document to retrieve. Can be a static value or a binding expression (e.g., from request query parameters or route parameters). No (if retrieving multiple documents or using other lookup methods)
partitionKey The partition key value for the document to retrieve. Required if your collection uses a partition key. Can be a static value or a binding expression. Conditional (Required for partitioned collections)
sqlQuery A SQL query to retrieve documents. If this is used, id and partitionKey are typically not used. Binding expressions can be used within the query. No

Using the Binding in C#

When using the input binding in C#, the retrieved document is passed as a parameter to your function. The type of the parameter depends on what you expect to retrieve.

Retrieving a Single Document

If you're retrieving a single document using its id, you can bind it to a class that matches the document structure, or to a dynamic type.

// function.json
// "id": "{Query.documentId}"

public class MyDocument
{
    public string Id { get; set; }
    public string Name { get; set; }
    // other properties
}

public static class CosmosDbInputExample
{
    [FunctionName("CosmosDbInputTrigger")]
    public static void Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "items/{documentId}")] HttpRequest req,
        string documentId,
        [CosmosDBInput(
            databaseName: "MyDatabase",
            collectionName: "MyCollection",
            ConnectionStringSetting = "CosmosDBConnectionString",
            Id = "{documentId}"
        )] MyDocument myInputDocument,
        ILogger log)
    {
        if (myInputDocument == null)
        {
            log.LogInformation($"Document with ID '{documentId}' not found.");
            return;
        }

        log.LogInformation($"Retrieved document: {JsonConvert.SerializeObject(myInputDocument)}");
        // Process the retrieved document
    }
}

Retrieving Multiple Documents with a Query

You can also use a SQL query to fetch multiple documents. The result can be bound to a collection type.

// function.json
// "sqlQuery": "SELECT * FROM c WHERE STARTSWITH(c.category, {Query.category})"

public static class CosmosDbQueryExample
{
    [FunctionName("CosmosDbQueryTrigger")]
    public static void Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "items/category/{category}")] HttpRequest req,
        string category,
        [CosmosDBInput(
            databaseName: "MyDatabase",
            collectionName: "MyCollection",
            ConnectionStringSetting = "CosmosDBConnectionString",
            SqlQuery = "SELECT * FROM c WHERE STARTSWITH(c.category, {category})"
        )] IEnumerable myInputDocuments,
        ILogger log)
    {
        if (myInputDocuments == null || !myInputDocuments.Any())
        {
            log.LogInformation($"No documents found for category starting with '{category}'.");
            return;
        }

        log.LogInformation($"Retrieved {myInputDocuments.Count()} documents.");
        foreach (var doc in myInputDocuments)
        {
            log.LogInformation($" - {doc.Name}");
        }
        // Process the retrieved documents
    }
}
Note: When using sqlQuery, make sure to properly escape any dynamic values within the query string. Azure Functions handles common cases, but complex scenarios might require explicit sanitization.

Connection Strings

The connection string for your Azure Cosmos DB account must be stored in your Azure Functions application settings. The name of this setting is specified in the connectionStringSetting parameter of your binding configuration.

You can find your connection string in the Azure portal under your Cosmos DB account's "Keys" blade.


# Example Application Setting (e.g., in local.settings.json)
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "CosmosDBConnectionString": "AccountEndpoint=https://your-cosmos-db.documents.azure.com:443/;AccountKey=your-account-key;"
  }
}

Learn More