Cosmos DB Bindings
Azure Functions provides robust bindings for interacting with Azure Cosmos DB, a globally distributed, multi-model database service. These bindings simplify common operations like reading documents, writing documents, and executing queries.
Input Bindings
Input bindings allow you to read data from Cosmos DB and make it available as parameters in your function. This is useful for retrieving specific documents or collections.
Reading a Single Document
You can configure a binding to fetch a single document based on its ID.
{
    "bindings": [
        {
            "name": "inputDocument",
            "type": "cosmosDB",
            "direction": "in",
            "databaseName": "MyDatabase",
            "collectionName": "MyCollection",
            "id": "{id}",
            "partitionKey": "{partitionKey}",
            "connectionStringSetting": "CosmosDBConnection"
        }
    ]
}In this configuration:
- name: The name of the parameter in your function.
- type: Specifies the binding type as- cosmosDB.
- direction: Set to- infor input bindings.
- databaseName: The name of your Cosmos DB database.
- collectionName: The name of your Cosmos DB container/collection.
- id: A binding expression that resolves to the document ID. This can be an HTTP route parameter, queue message content, etc.
- partitionKey: Similarly, a binding expression for the partition key.
- connectionStringSetting: The name of the application setting that holds your Cosmos DB connection string.
Reading Multiple Documents (Query)
For more complex data retrieval, you can use a SQL query.
{
    "bindings": [
        {
            "name": "outputDocuments",
            "type": "cosmosDB",
            "direction": "in",
            "databaseName": "MyDatabase",
            "collectionName": "MyCollection",
            "SqlQuery": "SELECT * FROM c WHERE c.status = 'active'",
            "connectionStringSetting": "CosmosDBConnection"
        }
    ]
}The SqlQuery property allows you to use standard Cosmos DB SQL syntax. The result will be a collection of documents.
Output Bindings
Output bindings enable you to write data to Cosmos DB. This is commonly used to save function results or new records.
Saving a Single Document
Save an object from your function to a Cosmos DB container.
{
    "bindings": [
        {
            "name": "outputDocument",
            "type": "cosmosDB",
            "direction": "out",
            "databaseName": "MyDatabase",
            "collectionName": "MyCollection",
            "createIfNotExists": true,
            "connectionStringSetting": "CosmosDBConnection"
        }
    ]
}In your function, you would assign an object to the outputDocument parameter:
// C# Example
public static void Run(TimerInfo myTimer, ILogger log, out MyDocument outputDocument)
{
    outputDocument = new MyDocument { Id = Guid.NewGuid().ToString(), Content = "Hello Cosmos DB!" };
    log.LogInformation($"Document created with ID: {outputDocument.Id}");
}The createIfNotExists property will create the container if it doesn't already exist.
API Reference
CosmosDB Binding Attributes
Input Binding (C#)
[CosmosDBInput(string databaseName, string collectionName, string ConnectionStringSetting = "", string Id = "", string SqlQuery = "", string PartitionKey = "")]Parameters:
- databaseName: string - The name of the Cosmos DB database.
- collectionName: string - The name of the Cosmos DB container.
- ConnectionStringSetting: string - The app setting name for the connection string.
- Id: string - The ID of the document to retrieve. Supports binding expressions.
- SqlQuery: string - The SQL query to execute.
- PartitionKey: string - The partition key for document retrieval. Supports binding expressions.
Output Binding (C#)
[CosmosDBOutput(string databaseName, string collectionName, string ConnectionStringSetting = "", string Id = "", bool CreateIfNotExists = false)]Parameters:
- databaseName: string - The name of the Cosmos DB database.
- collectionName: string - The name of the Cosmos DB container.
- ConnectionStringSetting: string - The app setting name for the connection string.
- Id: string - The ID of the document to save. Used for creating new documents if not specified.
- CreateIfNotExists: bool - If true, creates the container if it doesn't exist.
azure-functions-cosmosdb extension. For JavaScript, configure the bindings in function.json similarly to the JSON examples above.
            Common Scenarios
- Event Processing: Trigger a function when a new message arrives in a queue, read related data from Cosmos DB using an input binding, process it, and save the results back to Cosmos DB using an output binding.
- Data Synchronization: Periodically run a timer-triggered function to read data from an external source, transform it, and upsert it into a Cosmos DB container.
- API Backend: Create HTTP-triggered functions that fetch or save data to Cosmos DB, acting as a lightweight data API.
By leveraging Cosmos DB bindings, you can significantly reduce the amount of boilerplate code needed to interact with your database, allowing you to focus on your core application logic.