Azure Functions provide input and output bindings for Azure Cosmos DB, a globally distributed, multi-model database service. These bindings simplify interacting with your Cosmos DB collections by abstracting away the underlying SDKs and allowing you to focus on your function's logic.
Note: Ensure you have the appropriate Azure Functions extensions installed for Cosmos DB support.
Cosmos DB bindings in Azure Functions can be categorized into two main types:
Input bindings are used to retrieve data from Cosmos DB and make it available as parameters within your function. This can be a single document, a collection of documents, or the result of a SQL query.
Retrieve a single document by its ID.
function.json
{
  "bindings": [
    {
      "name": "inputDocument",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "id": "{id}",
      "partitionKey": "{partitionKey}",
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
        
        
C# (run.csx or C# Class Library)
using Microsoft.Azure.Documents;
public static void Run(IDocumentClient client, Document inputDocument, TraceWriter log)
{
    if (inputDocument != null)
    {
        log.Info($"Retrieved document: {inputDocument.Id}");
        // Process inputDocument here
    }
}
        
        
JavaScript (index.js)
module.exports = async function (context, inputDocument) {
    if (inputDocument) {
        context.log(`Retrieved document: ${inputDocument.id}`);
        // Process inputDocument here
    }
};
        
        
Python (function_app.py or __init__.py)
import logging
def main(inputDocument):
    if inputDocument:
        logging.info(f"Retrieved document: {inputDocument['id']}")
        # Process inputDocument here
        pass
        
        Retrieve all documents from a collection.
function.json
{
  "bindings": [
    {
      "name": "inputCollection",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
        
        C# (run.csx or C# Class Library) using Microsoft.Azure.Documents.Client; using System.Collections.Generic; public static void Run(IReadOnlyListinputCollection, TraceWriter log) { if (inputCollection != null) { log.Info($"Retrieved {inputCollection.Count} documents."); foreach (var doc in inputCollection) { log.Info($" Document ID: {doc.Id}"); } } } 
JavaScript (index.js)
module.exports = async function (context, inputCollection) {
    if (inputCollection) {
        context.log(`Retrieved ${inputCollection.length} documents.`);
        inputCollection.forEach(doc => {
            context.log(`  Document ID: ${doc.id}`);
        });
    }
};
        
        
Python (function_app.py or __init__.py)
import logging
def main(inputCollection):
    if inputCollection:
        logging.info(f"Retrieved {len(inputCollection)} documents.")
        for doc in inputCollection:
            logging.info(f"  Document ID: {doc['id']}")
        
        Retrieve documents based on a Cosmos DB SQL query.
function.json
{
  "bindings": [
    {
      "name": "outputDocument",
      "type": "cosmosDB",
      "direction": "out",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "createIfNotExists": false
    },
    {
      "name": "inputDocuments",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "SqlQuery": "SELECT * FROM c WHERE c.status = 'active'",
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
        
        
C# (run.csx or C# Class Library)
using Microsoft.Azure.Documents.Client;
using System.Collections.Generic;
public static void Run(IReadOnlyList<Document> inputDocuments, TraceWriter log)
{
    if (inputDocuments != null)
    {
        log.Info($"Retrieved {inputDocuments.Count} active documents.");
        foreach (var doc in inputDocuments)
        {
            log.Info($"  Document ID: {doc.Id}, Status: {doc.GetPropertyValue<string>("status")}");
        }
    }
}
        
        
JavaScript (index.js)
module.exports = async function (context, inputDocuments) {
    if (inputDocuments) {
        context.log(`Retrieved ${inputDocuments.length} active documents.`);
        inputDocuments.forEach(doc => {
            context.log(`  Document ID: ${doc.id}, Status: ${doc.status}`);
        });
    }
};
        
        
Python (function_app.py or __init__.py)
import logging
def main(inputDocuments):
    if inputDocuments:
        logging.info(f"Retrieved {len(inputDocuments)} active documents.")
        for doc in inputDocuments:
            logging.info(f"  Document ID: {doc['id']}, Status: {doc.get('status')}")
        
        Output bindings are used to write data to Cosmos DB. You can insert new documents or replace existing ones.
Insert or replace a document in Cosmos DB.
function.json
{
  "bindings": [
    {
      "name": "outputDocument",
      "type": "cosmosDB",
      "direction": "out",
      "databaseName": "MyDatabase",
      "collectionName": "MyCollection",
      "createIfNotExists": false,
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
        
        
C# (run.csx or C# Class Library)
using Microsoft.Azure.Documents;
using Newtonsoft.Json.Linq;
public static void Run(string inputPayload, out dynamic outputDocument, TraceWriter log)
{
    log.Info($"Processing payload: {inputPayload}");
    dynamic document = JObject.Parse(inputPayload);
    document.timestamp = DateTime.UtcNow;
    document.status = "processed";
    outputDocument = document;
    log.Info($"Writing document with ID: {document.id}");
}
        
        
JavaScript (index.js)
module.exports = async function (context, req) {
    context.log('HTTP trigger function processed a request.');
    const payload = req.body;
    if (!payload) {
        context.res = { status: 400, body: "Please provide a request body" };
        return;
    }
    payload.timestamp = new Date();
    payload.status = 'processed';
    context.bindings.outputDocument = payload;
    context.res = {
        status: 200,
        body: "Document processed and written to Cosmos DB"
    };
};
        
        
Python (function_app.py or __init__.py)
import logging
import azure.functions as func
import datetime
import json
def main(req: func.HttpRequest, outputDocument: func.Out[func.Document]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        payload = req.get_json()
    except ValueError:
        return func.HttpResponse("Please provide a valid JSON request body", status_code=400)
    if not payload:
        return func.HttpResponse("Please provide a request body", status_code=400)
    payload['timestamp'] = datetime.datetime.utcnow().isoformat()
    payload['status'] = 'processed'
    document = func.Document.from_dict(payload)
    outputDocument.set(document)
    return func.HttpResponse("Document processed and written to Cosmos DB", status_code=200)
        
        Cosmos DB bindings rely on connection strings defined in your function app's application settings. The `connectionStringSetting` property in function.json should refer to the name of the app setting that holds your Cosmos DB connection string.
Security Note: Never hardcode connection strings directly in your code or function.json. Always use application settings.
CosmosDBConnection:AccountEndpoint=https://mycosmosdb.documents.azure.com:443/;AccountKey=YOUR_ACCOUNT_KEY;DatabaseId=MyDatabase;
| Property | Description | Required | 
|---|---|---|
| name | The name of the parameter in your function's code. | Yes | 
| type | cosmosDBfor Cosmos DB bindings. | Yes | 
| direction | infor input bindings,outfor output bindings. | Yes | 
| databaseName | The name of the Cosmos DB database. | Yes | 
| collectionName | The name of the Cosmos DB collection (or container). | Yes | 
| connectionStringSetting | The name of the application setting that contains the Cosmos DB connection string. | Yes | 
| id | (Input only) The ID of the document to retrieve. Can use binding expressions like {id}. | No (for single document input, but required for specific doc retrieval) | 
| partitionKey | (Input only) The partition key value for the document to retrieve. Can use binding expressions. | No (required for specific doc retrieval when partition key is needed) | 
| SqlQuery | (Input only) A Cosmos DB SQL query to execute. | No | 
| createIfNotExists | (Output only) If true, the collection will be created if it doesn't exist. | No (defaults to false) | 
| sqlQueryTemplate | (Input only) A template for a SQL query that can be parameterized. | No | 
For more advanced scenarios like bulk operations, transactions, or custom SDK interactions, you may need to inject the IDocumentClient (for .NET) or use the Cosmos DB SDK directly within your function code.
Tip: When retrieving a collection using an input binding, the results are typically passed as an IReadOnlyList<Document> in .NET, an array in JavaScript, or a list of dictionaries in Python.