Azure Cosmos DB bindings for Azure Functions 1.x

This article explains how to work with Azure Cosmos DB bindings in Azure Functions. Azure Functions supports trigger, input, and output bindings for Azure Cosmos DB.

Note

This article is for Azure Functions 1.x. For information about how to use these bindings in Functions 2.x and higher, see Azure Cosmos DB bindings for Azure Functions 2.x.

This binding was originally named DocumentDB. In Azure Functions version 1.x, only the trigger was renamed Azure Cosmos DB; the input binding, output binding, and NuGet package retain the DocumentDB name.

Note

Azure Cosmos DB bindings are only supported for use with the SQL API. For all other Azure Cosmos DB APIs, you should access the database from your function by using the static client for your API, including Azure Cosmos DB for MongoDB, Azure Cosmos DB for Apache Cassandra, Azure Cosmos DB for Apache Gremlin, and Azure Cosmos DB for Table.

Packages - Functions 1.x

The Azure Cosmos DB bindings for Functions version 1.x are provided in the Microsoft.Azure.WebJobs.Extensions.DocumentDB NuGet package, version 1.x. Source code for the bindings is in the azure-webjobs-sdk-extensions GitHub repository.

The following table lists how to add support for output binding in each development environment.

Development environment To add support in Functions 1.x
Local development: C# class library Install the package
Local development: C# script, JavaScript, F# Automatic
Portal development Automatic

Trigger

The Azure Cosmos DB Trigger uses the Azure Cosmos DB Change Feed to listen for inserts and updates across partitions. The change feed publishes inserts and updates, not deletions.

Trigger - example

The following example shows an in-process C# function that is invoked when there are inserts or updates in the specified database and collection.

using Microsoft.Azure.Documents;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;

namespace CosmosDBSamplesV1
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "ToDoItems",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDBConnection",
            LeaseCollectionName = "leases",
            CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents,
            TraceWriter log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.Info($"Documents modified: {documents.Count}");
                log.Info($"First document Id: {documents[0].Id}");
            }
        }
    }
}

Trigger - attributes

For in-process C# class libraries, use the CosmosDBTrigger 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 Trigger - configuration. Here's a CosmosDBTrigger attribute example in a method signature:

    [FunctionName("DocumentUpdates")]
    public static void Run(
        [CosmosDBTrigger("database", "collection", ConnectionStringSetting = "myCosmosDB")]
    IReadOnlyList<Document> documents,
        TraceWriter log)
    {
        ...
    }

For a complete example, see Trigger - C# example.

Trigger - configuration

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

function.json property Attribute property Description
type n/a Must be set to cosmosDBTrigger.
direction n/a Must be set to in. This parameter is set automatically when you create the trigger in the Azure portal.
name n/a The variable name used in function code that represents the list of documents with changes.
connectionStringSetting ConnectionStringSetting The name of an app setting that contains the connection string used to connect to the Azure Cosmos DB account being monitored.
databaseName DatabaseName The name of the Azure Cosmos DB database with the collection being monitored.
collectionName CollectionName The name of the collection being monitored.
leaseConnectionStringSetting LeaseConnectionStringSetting (Optional) The name of an app setting that contains the connection string to the service which holds the lease collection. When not set, the connectionStringSetting value is used. This parameter is automatically set when the binding is created in the portal. The connection string for the leases collection must have write permissions.
leaseDatabaseName LeaseDatabaseName (Optional) The name of the database that holds the collection used to store leases. When not set, the value of the databaseName setting is used. This parameter is automatically set when the binding is created in the portal.
leaseCollectionName LeaseCollectionName (Optional) The name of the collection used to store leases. When not set, the value leases is used.
createLeaseCollectionIfNotExists CreateLeaseCollectionIfNotExists (Optional) When set to true, the leases collection is automatically created when it doesn't already exist. The default value is false.
leasesCollectionThroughput LeasesCollectionThroughput (Optional) Defines the amount of Request Units to assign when the leases collection is created. This setting is only used When createLeaseCollectionIfNotExists is set to true. This parameter is automatically set when the binding is created using the portal.
leaseCollectionPrefix LeaseCollectionPrefix (Optional) When set, it adds a prefix to the leases created in the Lease collection for this Function, effectively allowing two separate Azure Functions to share the same Lease collection by using different prefixes.
feedPollDelay FeedPollDelay (Optional) When set, it defines, in milliseconds, the delay in between polling a partition for new changes on the feed, after all current changes are drained. Default is 5000 (5 seconds).
leaseAcquireInterval LeaseAcquireInterval (Optional) When set, it defines, in milliseconds, the interval to kick off a task to compute if partitions are distributed evenly among known host instances. Default is 13000 (13 seconds).
leaseExpirationInterval LeaseExpirationInterval (Optional) When set, it defines, in milliseconds, the interval for which the lease is taken on a lease representing a partition. If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will move to another instance. Default is 60000 (60 seconds).
leaseRenewInterval LeaseRenewInterval (Optional) When set, it defines, in milliseconds, the renew interval for all leases for partitions currently held by an instance. Default is 17000 (17 seconds).
checkpointFrequency CheckpointFrequency (Optional) When set, it defines, in milliseconds, the interval between lease checkpoints. Default is always after each Function call.
maxItemsPerInvocation MaxItemsPerInvocation (Optional) When set, it customizes the maximum amount of items received per Function call.
startFromBeginning StartFromBeginning (Optional) When set, it tells the Trigger to start reading changes from the beginning of the history of the collection instead of the current time. This only works the first time the Trigger starts, as in subsequent runs, the checkpoints are already stored. Setting this to true when there are leases already created has no effect.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Trigger - usage

The trigger requires a second collection that it uses to store leases over the partitions. Both the collection being monitored and the collection that contains the leases must be available for the trigger to work.

Important

If multiple functions are configured to use an Azure Cosmos DB trigger for the same collection, each of the functions should use a dedicated lease collection or specify a different LeaseCollectionPrefix for each function. Otherwise, only one of the functions will be triggered. For information about the prefix, see the Configuration section.

The trigger doesn't indicate whether a document was updated or inserted, it just provides the document itself. If you need to handle updates and inserts differently, you could do that by implementing timestamp fields for insertion or update.

Input

The Azure Cosmos DB input binding uses the SQL API to retrieve one or more Azure Cosmos DB documents and passes them to the input parameter of the function. The document ID or query parameters can be determined based on the trigger that invokes the function.

Input - example

This section contains the following examples:

The examples refer to a simple ToDoItem type:

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

Queue trigger, look up ID from JSON

The following example shows a C# function that retrieves a single document. The function is triggered by a queue message that contains a JSON object. The queue trigger parses the JSON into an object named ToDoItemLookup, which contains the ID to look up. That ID is used to retrieve a ToDoItem document from the specified database and collection.

namespace CosmosDBSamplesV1
{
    public class ToDoItemLookup
    {
        public string ToDoItemId { get; set; }
    }
}
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromJSON
    {
        [FunctionName("DocByIdFromJSON")]
        public static void Run(
            [QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{ToDoItemId}")]ToDoItem toDoItem,
            TraceWriter log)
        {
            log.Info($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId}");

            if (toDoItem == null)
            {
                log.Info($"ToDo item not found");
            }
            else
            {
                log.Info($"Found ToDo item, Description={toDoItem.Description}");
            }
        }
    }
}

HTTP trigger, look up ID from query string

The following example shows a C# function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID to look up. That ID is used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromQueryString
    {
        [FunctionName("DocByIdFromQueryString")]
        public static HttpResponseMessage Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{Query.id}")] ToDoItem toDoItem,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (toDoItem == null)
            {
                log.Info($"ToDo item not found");
            }
            else
            {
                log.Info($"Found ToDo item, Description={toDoItem.Description}");
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

HTTP trigger, look up ID from route data

The following example shows a C# function that retrieves a single document. The function is triggered by an HTTP request that uses route data to specify the ID to look up. That ID is used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromRouteData
    {
        [FunctionName("DocByIdFromRouteData")]
        public static HttpResponseMessage Run(
            [HttpTrigger(
                AuthorizationLevel.Anonymous, "get", "post",
                Route = "todoitems/{id}")]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{id}")] ToDoItem toDoItem,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            if (toDoItem == null)
            {
                log.Info($"ToDo item not found");
            }
            else
            {
                log.Info($"Found ToDo item, Description={toDoItem.Description}");
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

Skip input examples

HTTP trigger, look up ID from route data, using SqlQuery

The following example shows a C# function that retrieves a single document. The function is triggered by an HTTP request that uses route data to specify the ID to look up. That ID is used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromRouteDataUsingSqlQuery
    {
        [FunctionName("DocByIdFromRouteDataUsingSqlQuery")]
        public static HttpResponseMessage Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
                Route = "todoitems2/{id}")]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                SqlQuery = "select * from ToDoItems r where r.id = {id}")] IEnumerable<ToDoItem> toDoItems,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            foreach (ToDoItem toDoItem in toDoItems)
            {
                log.Info(toDoItem.Description);
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

Skip input examples

HTTP trigger, get multiple docs, using SqlQuery

The following example shows a C# function that retrieves a list of documents. The function is triggered by an HTTP request. The query is specified in the SqlQuery attribute property.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocsBySqlQuery
    {
        [FunctionName("DocsBySqlQuery")]
        public static HttpResponseMessage Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
                HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                SqlQuery = "SELECT top 2 * FROM c order by c._ts desc")]
                IEnumerable<ToDoItem> toDoItems,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            foreach (ToDoItem toDoItem in toDoItems)
            {
                log.Info(toDoItem.Description);
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

Skip input examples

HTTP trigger, get multiple docs, using DocumentClient (C#)

The following example shows a C# function that retrieves a list of documents. The function is triggered by an HTTP request. The code uses a DocumentClient instance provided by the Azure Cosmos DB binding to read a list of documents. The DocumentClient instance could also be used for write operations.

using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace CosmosDBSamplesV1
{
    public static class DocsByUsingDocumentClient
    {
        [FunctionName("DocsByUsingDocumentClient")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")] DocumentClient client,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
            string searchterm = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "searchterm", true) == 0)
                .Value;

            if (searchterm == null)
            {
                return req.CreateResponse(HttpStatusCode.NotFound);
            }

            log.Info($"Searching for word: {searchterm} using Uri: {collectionUri.ToString()}");
            IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
                .Where(p => p.Description.Contains(searchterm))
                .AsDocumentQuery();

            while (query.HasMoreResults)
            {
                foreach (ToDoItem result in await query.ExecuteNextAsync())
                {
                    log.Info(result.Description);
                }
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

Input - attributes

In in-process C# class libraries, use the DocumentDB 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 the following configuration section.

Input - configuration

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

function.json property Attribute property Description
type n/a Must be set to documentdb.
direction n/a Must be set to in.
name n/a Name of the binding parameter that represents the document in the function.
databaseName DatabaseName The database containing the document.
collectionName CollectionName The name of the collection that contains the document.
id Id The ID of the document to retrieve. This property supports binding expressions. Don't set both the id and sqlQuery properties. If you don't set either one, the entire collection is retrieved.
sqlQuery SqlQuery An Azure Cosmos DB SQL query used for retrieving multiple documents. The property supports runtime bindings, as in this example: SELECT * FROM c where c.departmentId = {departmentId}. Don't set both the id and sqlQuery properties. If you don't set either one, the entire collection is retrieved.
connection ConnectionStringSetting The name of the app setting containing your Azure Cosmos DB connection string.
partitionKey PartitionKey Specifies the partition key value for the lookup. May include binding parameters.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Input - usage

When the function exits successfully, any changes made to the input document via named input parameters are automatically persisted.

Output

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

Output - example

This section contains the following examples:

  • Queue trigger, write one doc
  • Queue trigger, write docs using IAsyncCollector

The examples refer to a simple ToDoItem type:

namespace CosmosDBSamplesV1
{
    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 System;

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

            log.Info($"C# Queue trigger function inserted one row");
            log.Info($"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;

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

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

Output - attributes

In in-process C# class libraries, use the DocumentDB 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 DocumentDB attribute example in a method signature:

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

For a complete example, see Output.

Output - configuration

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

function.json property Attribute property Description
type n/a Must be set to documentdb.
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 CollectionName The name of the collection where the document is created.
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, defines the partition key path for the created collection.
collectionThroughput CollectionThroughput When CreateIfNotExists is true, defines the throughput of the created collection.
connection ConnectionStringSetting The name of the app setting containing your Azure Cosmos DB connection string.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Output - 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
Azure Cosmos DB HTTP status codes for Azure Cosmos DB

Next steps