The Azure Cosmos DB output binding allows your Azure Functions to write data to a Cosmos DB collection. This binding is useful for scenarios where your function needs to persist or send data to Cosmos DB, such as logging, storing results, or updating records.

Prerequisites

  • An Azure subscription.
  • An Azure Cosmos DB account and database.
  • An Azure Function App created.
  • The Cosmos DB output binding extension installed (if not using the v2 programming model).

Configuration

The Cosmos DB output binding is configured in your function's function.json file (for the v1 programming model) or using attributes in your code (for the v2 programming model).

function.json Example (v1 Model)

{
    "scriptFile": "run.csx",
    "bindings": [
        {
            "name": "req",
            "type": "httpTrigger",
            "direction": "in",
            "methods": [ "get", "post" ]
        },
        {
            "name": "outputDocument",
            "type": "cosmosDB",
            "direction": "out",
            "databaseName": "MyDatabase",
            "collectionName": "MyCollection",
            "connectionStringSetting": "CosmosDBConnectionString"
        },
        {
            "name": "res",
            "type": "http",
            "direction": "out"
        }
    ]
}

Attribute Example (C# v2 Model)

public static class CosmosDbOutputFunction
{
    [FunctionName("CosmosDbOutput")]
    public static void Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
        [CosmosDB(
            databaseName: "MyDatabase",
            collectionName: "MyCollection",
            ConnectionStringSetting = "CosmosDBConnectionString"
        )] out dynamic outputDocument)
    {
        string requestBody = new StreamReader(req.Body).ReadToEnd();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        outputDocument = data;
    }
}

Binding Properties

The following table describes the configuration properties for the Cosmos DB output binding:

Property Description Required Type Default
name The name of the output binding. This is used to reference the binding in your code. Yes String N/A
type Must be set to cosmosDB. Yes String N/A
direction Must be set to out. Yes String N/A
databaseName The name of the Cosmos DB database. Yes String N/A
collectionName The name of the Cosmos DB collection. Yes String N/A
connectionStringSetting The name of the application setting that contains your Cosmos DB connection string. Yes String N/A
createNewCollection If set to true, the collection will be created if it doesn't exist. No Boolean false
partitionKey Specifies the partition key value for the document. This is required if your collection has a partition key defined. No String N/A

Using the Output Binding in Code

The output binding is typically used by assigning a value to the bound variable. The binding mechanism will then serialize and send this value to Cosmos DB.

JavaScript Example

module.exports = async function (context, req) {
    const item = {
        id: context.bindingData.id, // Assuming 'id' is passed in HTTP query or body
        name: req.body.name,
        value: req.body.value
    };

    context.bindings.outputDocument = item; // Assign to the output binding
    context.res = {
        status: 200,
        body: "Item created successfully."
    };
};

C# Example (v1 Model)

using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

public static class CosmosDbOutputFunctionCSharp
{
    [FunctionName("CosmosDbOutputCSharp")]
    public static async Task Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
        [CosmosDB(
            databaseName: "MyDatabase",
            collectionName: "MyCollection",
            ConnectionStringSetting = "CosmosDBConnectionString"
        )] out dynamic outputDocument, // Use 'out' keyword for output binding
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);

        // Create a unique ID if not provided
        if (data?.id == null)
        {
            data.id = System.Guid.NewGuid().ToString();
        }

        outputDocument = data; // Assign the data to the output binding

        log.LogInformation($"Document written to Cosmos DB: {data.id}");
    }
}

Partition Key Handling

If your Cosmos DB collection is partitioned, you must provide a partition key value when writing documents. This can be done in several ways:

  • In the Function Signature (v2 Model): You can bind the partition key from another input binding or HTTP trigger parameter.
  • In your code: You can explicitly set the partition key property on the object you are writing.
  • Via HTTP Headers: For HTTP-triggered functions, you can sometimes pass the partition key in a custom HTTP header.

Important Considerations

  • Ensure your Cosmos DB connection string is stored securely as an application setting.
  • When creating a new collection with createNewCollection: true, you must also define its throughput and partition key in the function.json or relevant attribute.
  • Error handling is crucial. Implement logic to catch potential exceptions during the write operation.

Common Use Cases

  • Storing logs and telemetry data.
  • Persisting the results of function executions.
  • Updating or creating records in response to events.
  • Implementing CQRS patterns by writing events to Cosmos DB.

Tip

Consider using Cosmos DB's Change Feed to trigger other functions when data is written or updated via this output binding.