Cosmos DB Input Bindings

Cosmos DB input bindings allow you to read data from a Cosmos DB collection within your Azure Function. This binding can fetch a single document, multiple documents based on a query, or the entire collection.

When to Use

Use Cosmos DB input bindings when your function needs to access data stored in Azure Cosmos DB to perform its logic. This is common for scenarios like:

Supported Bindings

The Cosmos DB input binding supports the following scenarios:

1. Fetching a Single Document by ID

You can fetch a single document using its unique ID. The ID can be provided directly, or dynamically from a trigger input or other binding.

Configuration (function.json)


{
  "bindings": [
    {
      "name": "inputDocument",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "connectionStringSetting": "CosmosDBConnection",
      "id": "{id}"
    }
    // ... other bindings
  ]
}
            

Code Example (C#)


using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

public static class GetCosmosDoc
{
    [FunctionName("GetCosmosDoc")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "items/{id}")] HttpRequestMessage req,
        string id,
        [CosmosDB(
            databaseName: "MyDatabase",
            collectionName: "MyCollection",
            ConnectionStringSetting = "CosmosDBConnection",
            Id = "{id}"
        )] dynamic inputDocument,
        TraceWriter log)
    {
        log.Info($"C# HTTP trigger function processed a request for ID: {id}.");

        if (inputDocument == null)
        {
            return new NotFoundResult();
        }

        return new OkObjectResult(inputDocument);
    }
}
            

2. Fetching Multiple Documents with a Query

You can retrieve multiple documents that match a specified SQL query. The query can be static or dynamic.

Configuration (function.json)


{
  "bindings": [
    {
      "name": "inputDocuments",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "connectionStringSetting": "CosmosDBConnection",
      "SqlQuery": "SELECT * FROM c WHERE c.category = {category}"
    }
    // ... other bindings
  ]
}
            

Code Example (JavaScript)


// JavaScript example
// ...
// Using binding:
// "bindings": [
//   {
//     "name": "inputDocuments",
//     "type": "cosmosDB",
//     "direction": "in",
//     "databaseName": "MyDatabase",
//     "collectionName": "MyCollection",
//     "connectionStringSetting": "CosmosDBConnection",
//     "SqlQuery": "SELECT * FROM c WHERE c.category = {category}"
//   }
// ]
// In function:
// module.exports = async function (context, req, inputDocuments) {
//     context.log('JavaScript HTTP trigger function processed a request.');
//     if (inputDocuments && inputDocuments.length > 0) {
//         context.res = {
//             status: 200,
//             body: inputDocuments
//         };
//     } else {
//         context.res = {
//             status: 404,
//             body: "No documents found for the given category"
//         };
//     }
// };
            

When using SqlQuery, the id property should not be set.

3. Fetching All Documents in a Collection

To retrieve all documents from a collection, simply omit the id and SqlQuery properties.

Configuration (function.json)


{
  "bindings": [
    {
      "name": "allDocuments",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "connectionStringSetting": "CosmosDBConnection"
    }
    // ... other bindings
  ]
}
            

Important Considerations

  • Connection String: Ensure your connectionStringSetting points to a valid Cosmos DB connection string in your application settings.
  • Indexing: For efficient queries, ensure your Cosmos DB collections are properly indexed.
  • Partition Keys: If your collection uses partition keys, ensure your queries are designed to utilize them effectively to avoid cross-partition queries, which can be less performant and more costly.
  • Error Handling: Implement robust error handling for cases where documents are not found or connection issues arise.
  • Data Types: Be mindful of the data types when mapping Cosmos DB documents to your function's code.

Language-Specific Notes

The specific syntax and how the bound data is passed to your function will vary slightly based on the programming language you are using:

Always refer to the official Azure Functions documentation for the most up-to-date information and detailed examples for your specific language and version.