Azure Cosmos DB output binding for Azure Functions 2.x and higher

The Azure Cosmos DB output binding lets you write a new document to an Azure Cosmos DB database using the SQL API.

For information on setup and configuration details, see the overview.

This section contains the following examples:

The examples refer to a simple ToDoItem type:

namespace CosmosDBSamplesV2
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
    }
}

Queue trigger, write one doc

The following example shows a C# function that adds a document to a database, using data provided in message from Queue storage.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using System;

namespace CosmosDBSamplesV2
{
    public static class WriteOneDoc
    {
        [FunctionName("WriteOneDoc")]
        public static void Run(
            [QueueTrigger("todoqueueforwrite")] string queueMessage,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")]out dynamic document,
            ILogger log)
        {
            document = new { Description = queueMessage, id = Guid.NewGuid() };

            log.LogInformation($"C# Queue trigger function inserted one row");
            log.LogInformation($"Description={queueMessage}");
        }
    }
}

Queue trigger, write one doc (v4 extension)

Apps using Cosmos DB extension version 4.x or higher will have different attribute properties which are shown below. The following example shows a C# function that adds a document to a database, using data provided in message from Queue storage.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using System;

namespace CosmosDBSamplesV2
{
    public static class WriteOneDoc
    {
        [FunctionName("WriteOneDoc")]
        public static void Run(
            [QueueTrigger("todoqueueforwrite")] string queueMessage,
            [CosmosDB(
                databaseName: "ToDoItems",
                containerName: "Items",
                Connection = "CosmosDBConnection")]out dynamic document,
            ILogger log)
        {
            document = new { Description = queueMessage, id = Guid.NewGuid() };

            log.LogInformation($"C# Queue trigger function inserted one row");
            log.LogInformation($"Description={queueMessage}");
        }
    }
}

Queue trigger, write docs using IAsyncCollector

The following example shows a C# function that adds a collection of documents to a database, using data provided in a queue message JSON.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class WriteDocsIAsyncCollector
    {
        [FunctionName("WriteDocsIAsyncCollector")]
        public static async Task Run(
            [QueueTrigger("todoqueueforwritemulti")] ToDoItem[] toDoItemsIn,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")]
                IAsyncCollector<ToDoItem> toDoItemsOut,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

            foreach (ToDoItem toDoItem in toDoItemsIn)
            {
                log.LogInformation($"Description={toDoItem.Description}");
                await toDoItemsOut.AddAsync(toDoItem);
            }
        }
    }
}

Attributes and annotations

In C# class libraries, use the CosmosDB attribute.

The attribute's constructor takes the database name and collection name. For information about those settings and other properties that you can configure, see Output - configuration. Here's a CosmosDB attribute example in a method signature:

    [FunctionName("QueueToDocDB")]
    public static void Run(
        [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] string myQueueItem,
        [CosmosDB("ToDoList", "Items", Id = "id", ConnectionStringSetting = "myCosmosDB")] out dynamic document)
    {
        ...
    }

In extension version 4.x some settings and properties have been removed or renamed. For detailed information about the changes, see Output - configuration. Here's a CosmosDB attribute example in a method signature:

    [FunctionName("QueueToCosmosDB")]
    public static void Run(
      [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] string myQueueItem,
      [CosmosDB("database", "container", Connection = "CosmosDBConnectionSetting")] out dynamic document)
    {
        ...
    }

Configuration

The following table explains the binding configuration properties that you set in the function.json file and the CosmosDB attribute.

function.json property Attribute property Description
type n/a Must be set to cosmosDB.
direction n/a Must be set to out.
name n/a Name of the binding parameter that represents the document in the function.
databaseName DatabaseName The database containing the collection where the document is created.
collectionName
or
containerName
CollectionName
or
ContainerName
The name of the collection where the document is created.

In version 4.x of the extension this property is called ContainerName.
createIfNotExists CreateIfNotExists A boolean value to indicate whether the collection is created when it doesn't exist. The default is false because new collections are created with reserved throughput, which has cost implications. For more information, see the pricing page.
partitionKey PartitionKey When CreateIfNotExists is true, it defines the partition key path for the created collection.
collectionThroughput
or
containerThroughput
CollectionThroughput
or
ContainerThroughput
When CreateIfNotExists is true, it defines the throughput of the created collection.

In version 4.x of the extension this property is called ContainerThroughput.
connectionStringSetting
or
connection
ConnectionStringSetting
or
Connection
The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account. See Connections

In version 4.x of the extension this property is called connection.
preferredLocations PreferredLocations (Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Values should be comma-separated. For example, "East US,South Central US,North Europe".
useMultipleWriteLocations UseMultipleWriteLocations (Optional) When set to true along with PreferredLocations, it can leverage multi-region writes in the Azure Cosmos DB service.

This property is not available in version 4.x of the extension.

When you're developing locally, app settings go into the local.settings.json file.

Connections

The connectionStringSetting/connection and leaseConnectionStringSetting/leaseConnection properties are references to environment configuration which specifies how the app should connect to Azure Cosmos DB. They may specify:

If the configured value is both an exact match for a single setting and a prefix match for other settings, the exact match is used.

Connection string

The connection string for your database account should be stored in an application setting with a name matching the value specified by the connection property of the binding configuration.

Identity-based connections

If you are using version 4.x or higher of the extension, instead of using a connection string with a secret, you can have the app use an Azure Active Directory identity. To do this, you would define settings under a common prefix which maps to the connection property in the trigger and binding configuration.

In this mode, the extension requires the following properties:

Property Environment variable template Description Example value
Account Endpoint <CONNECTION_NAME_PREFIX>__accountEndpoint The Azure Cosmos DB account endpoint URI. <database_account_name>.documents.azure.com

Additional properties may be set to customize the connection. See Common properties for identity-based connections.

When hosted in the Azure Functions service, identity-based connections use a managed identity. The system-assigned identity is used by default, although a user-assigned identity can be specified with the credential and clientID properties. When run in other contexts, such as local development, your developer identity is used instead, although this can be customized. See Local development with identity-based connections.

Grant permission to the identity

Whatever identity is being used must have permissions to perform the intended actions. You will need to assign a role in Azure RBAC, using either built-in or custom roles which provide those permissions.

Important

Some permissions might be exposed by the target service that are not necessary for all contexts. Where possible, adhere to the principle of least privilege, granting the identity only required privileges. For example, if the app only needs to be able to read from a data source, use a role that only has permission to read. It would be inappropriate to assign a role that also allows writing to that service, as this would be excessive permission for a read operation. Similarly, you would want to ensure the role assignment is scoped only over the resources that need to be read.

You will need to create a role assignment that provides access to your database account at runtime. Management roles like Owner are not sufficient. The following table shows built-in roles that are recommended when using the Cosmos DB extension in normal operation. Your application may require additional permissions based on the code you write.

Binding type Example built-in roles
Trigger Cosmos DB Built-in Data Contributor
Input binding Cosmos DB Built-in Data Reader
Output binding Cosmos DB Built-in Data Contributor

Usage

By default, when you write to the output parameter in your function, a document is created in your database. This document has an automatically generated GUID as the document ID. You can specify the document ID of the output document by specifying the id property in the JSON object passed to the output parameter.

Note

When you specify the ID of an existing document, it gets overwritten by the new output document.

Exceptions and return codes

Binding Reference
CosmosDB CosmosDB Error Codes

host.json settings

This section describes the configuration settings available for this binding in versions 2.x and higher. Settings in the host.json file apply to all functions in a function app instance. The example host.json file below contains only the version 2.x+ settings for this binding. For more information about function app configuration settings in versions 2.x and later versions, see host.json reference for Azure Functions.

{
    "version": "2.0",
    "extensions": {
        "cosmosDB": {
            "connectionMode": "Gateway",
            "protocol": "Https",
            "leaseOptions": {
                "leasePrefix": "prefix1"
            }
        }
    }
}
Property Default Description
GatewayMode Gateway The connection mode used by the function when connecting to the Azure Cosmos DB service. Options are Direct and Gateway
Protocol Https The connection protocol used by the function when connection to the Azure Cosmos DB service. Read here for an explanation of both modes.

This setting is not available in version 4.x of the extension.
leasePrefix n/a Lease prefix to use across all functions in an app.

This setting is not available in version 4.x of the extension.

Next steps