Cosmos DB Output Bindings

This document explains how to configure and use Azure Functions output bindings for Cosmos DB. Cosmos DB output bindings enable your functions to write data to a Cosmos DB collection.

Overview

Cosmos DB output bindings simplify the process of persisting data from your Azure Functions to Azure Cosmos DB, a globally distributed, multi-model database service. You can configure your function to automatically insert or update documents in a specified Cosmos DB container based on the return value of your function or an explicit output binding.

Configuration

Output bindings are defined in your function's function.json file. For Cosmos DB output bindings, you typically specify the following properties:

Example function.json


{
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "cosmosDB",
      "direction": "out",
      "name": "outputDocument",
      "databaseName": "MyDatabase",
      "collectionName": "MyItems",
      "connectionStringSetting": "CosmosDbConnectionString"
    }
  ],
  "disabled": false
}
            

Using the Binding in Code

The name property in function.json (e.g., outputDocument) corresponds to a parameter in your function's code. You can assign the document you want to save to this parameter.

C# Example


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

public static class CreateCosmosDbItem
{
    [FunctionName("CreateCosmosDbItem")]
    public static async Task Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
        [CosmosDB(
            databaseName: "MyDatabase",
            collectionName: "MyItems",
            ConnectionStringSetting = "CosmosDbConnectionString")] IAsyncCollector outputDocument,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request to create a Cosmos DB item.");

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

        if (data == null)
        {
            return new BadRequestObjectResult("Please pass an item in the request body");
        }

        // The Cosmos DB output binding will automatically save 'data' to the collection
        await outputDocument.AddAsync(data);

        return new OkObjectResult($"Item with ID '{data.id}' was created successfully.");
    }
}
            

Node.js Example


module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request to create a Cosmos DB item.');

    const item = req.body;

    if (item) {
        // Assign the item to the output binding context
        context.bindings.outputDocument = item;
        context.res = {
            status: 201,
            body: `Item with ID '${item.id}' was created successfully.`
        };
    } else {
        context.res = {
            status: 400,
            body: "Please pass an item in the request body"
        };
    }
};
            

Important Considerations

Note: For Cosmos DB output bindings, the document must have an id property. If it doesn't, Cosmos DB will generate one, but it's best practice to provide it explicitly for predictability.
Important: Ensure your CosmosDbConnectionString application setting is correctly configured in your Azure Functions App. This connection string should grant write permissions to your Cosmos DB account.
Warning: Be mindful of the throughput provisioned for your Cosmos DB collection. High volumes of writes from multiple functions can impact performance and cost.

Upserting Documents

By default, the Cosmos DB output binding performs an insert operation. If a document with the same ID already exists, it will result in an error. To perform an upsert (insert or update), you can leverage the Upsert property in certain SDKs or by using the Cosmos DB SDK directly within your function if more granular control is needed. However, for many scenarios, the basic output binding behavior is sufficient for inserts.

Next Steps