Edit

Share via


Azure Cosmos DB for MongoDB (vCore) trigger for Azure Functions

This article explains how to work with the Azure Cosmos DB for MongoDB vCore trigger in Azure Functions. The bindings use change streams in Azure Cosmos DB’s API for MongoDB to listen for inserts and updates.

The change feed publishes only new and updated items. Watching for delete operations using change streams is currently not supported.

Important

The Azure Cosmos DB for MongoDB (vCore) extension is currently in preview.
At this time, only .NET apps that use the in-process model are supported.

Example

This example shows a function that returns a single document that is inserted or updated:

[FunctionName("TriggerSample")]
public static void TriggerRun(
  [CosmosDBMongoTrigger("TestDatabase", "TestCollection")] ChangeStreamDocument<BsonDocument> doc,
  ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

    log.LogInformation(doc.FullDocument.ToString());
}

For the complete example, see Sample.cs in the extension repository.

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 being monitored by the trigger for changes. Required unless TriggerLevel is set to MonitorLevel.Cluser.
CollectionName The name of the collection in the database being monitored by the trigger for changes. Required when TriggerLevel is set to MonitorLevel.Collection.
ConnectionStringSetting The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account being monitored.
TriggerLevel Indicates the level at which changes are being monitored. Valid values of MonitorLevel are: Collection, Database, and Cluster.

Usage

Use the TriggerLevel parameter to set the scope of changes being monitored.

You can use the CosmosDBMongo attribute to obtain and work directly with the MongoDB client in your function code:

[FunctionName("ClientBindingSample")]
public static void ClientBindingRun(
     [TimerTrigger("*/5 * * * * *")] TimerInfo myTimer,
     [CosmosDBMongo] IMongoClient client,
     ILogger log)
{
    var documents = client.GetDatabase("TestDatabase").GetCollection<BsonDocument>("TestCollection").Find(new BsonDocument()).ToList();

    foreach (BsonDocument d in documents)
    {
        log.LogInformation(d.ToString());
    }
}