Edit

Share via


Azure DocumentDB output binding for Azure Functions

Important

The Azure DocumentDB extension is currently in preview. At this time, only .NET apps that use the legacy in-process model are supported.

The Azure DocumentDB output binding lets you write new documents to an Azure DocumentDB collection from your Azure Functions. This article explains how to configure and use the output binding, including code examples for writing documents to your database.

Prerequisites

Example

This example shows an HTTP trigger function for an HTTP POST request. The request gets an expected string in the request body. Then the output binding adds a document to the collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs.Extensions.AzureCosmosDb.Mongo;
using MongoDB.Bson;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Mvc;

public static class DocumentDBOutput
{
    [FunctionName(nameof(DocumentDBOutput))]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "POST", Route = null)]
        string payload,
        [CosmosDBMongo(databaseName: "<database-name>",
                        collectionName: "<collection-name>",
                        ConnectionStringSetting = "<name-of-app-setting>")]
        IAsyncCollector<BsonDocument> collector,
        ILogger logger)
    {
        logger.LogInformation("C# Azure DocumentDB output function starting.");

        BsonDocument document = new()
        {
            { "message", payload },
            { "originator", nameof(DocumentDBOutput) },
            { "timestamp", BsonDateTime.Create(System.DateTime.UtcNow) }
        };

        await collector.AddAsync(document);

        return new OkObjectResult("Document added successfully.");
    }
}

Alternatively, use a C# record or class type to represent documents to add to the collection:

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs.Extensions.AzureCosmosDb.Mongo;
using MongoDB.Bson;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson.Serialization.Attributes;

public static class DocumentDBOutput
{
    [FunctionName(nameof(DocumentDBOutput))]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "POST", Route = null)]
        ProductDocument payload,
        [CosmosDBMongo(databaseName: "<database-name>",
                        collectionName: "<collection-name>",
                        ConnectionStringSetting = "<name-of-app-setting>")]
        IAsyncCollector<ProductDocument> collector,
        ILogger logger)
    {
        logger.LogInformation("C# Azure DocumentDB output function starting.");

        await collector.AddAsync(payload);

        return new OkObjectResult("Document added successfully.");
    }
}

public sealed record ProductDocument(
    [property: BsonId]
    [property: BsonRepresentation(BsonType.ObjectId)] string id,
    string name,
    string category,
    int quantity,
    decimal price,
    bool sale
);

Attributes

This table describes the binding configuration properties of the CosmosDBMongoTrigger attribute.

Parameter Description
FunctionId (Optional) The ID of the trigger function.
DatabaseName The name of the database targeted for the output data.
CollectionName The name of the collection in the database targeted for the output data.
ConnectionStringSetting The name of an app setting or setting collection that specifies how to connect to the Azure DocumentDB cluster targeted for the output data.
CreateIfNotExists (Optional) When set to true, creates the targeted collection if it doesn't already exist.

Usage

Use the CosmosDBMongo attribute to insert a set of documents into a collection that might not exist:

[FunctionName(nameof(DocumentDBOutput))]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "POST", Route = null)]
    BsonDocument payload,
    [CosmosDBMongo(databaseName: "<database-name>",
                    collectionName: "products",
                    ConnectionStringSetting = "<name-of-app-setting>",
                    CreateIfNotExists = true)]
    IAsyncCollector<BsonDocument> collector,
    ILogger logger)
{
    logger.LogInformation("C# Azure DocumentDB output function starting.");

    await collector.AddAsync(payload);

    return new OkObjectResult("Document added successfully.");
}

Alternatively, work directly with the MongoDB client in your function code:

[FunctionName(nameof(DocumentDBOutput))]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "POST", Route = null)]
    BsonDocument payload,
    [CosmosDBMongo(ConnectionStringSetting = "<name-of-app-setting>")]
    IMongoClient client,
    ILogger logger)
{
    logger.LogInformation("C# Azure DocumentDB function got a client.");

    IMongoDatabase database = client.GetDatabase("<database-name>");

    IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("<collection-name>");

    await collection.InsertOneAsync(payload);

    return new OkObjectResult("Document added successfully.");
}