Edit

Share via


Azure Cosmos DB for MongoDB (vCore) input binding for Azure Functions

This article explains how to work with the Azure Cosmos DB for MongoDB vCore input binding in Azure Functions.

The Azure Cosmos DB for MongoDB (vCore) input binding lets you retrieve one or more items as documents from the database.

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 Timer trigger function that uses an input binding to execute a periodic query against the database:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.AzureCosmosDb.Mongo;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Sample
{
    public static class Sample
    {
         [FunctionName("InputBindingSample")]
          public static async Task InputBindingRun(
            [TimerTrigger("*/5 * * * * *")] TimerInfo myTimer,
            [CosmosDBMongo("%vCoreDatabaseTrigger%", "%vCoreCollectionTrigger%", ConnectionStringSetting = "vCoreConnectionStringTrigger",
            QueryString = "%queryString%")] List<BsonDocument> docs,
            ILogger log)
          {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            foreach (var doc in docs)
            {
                log.LogInformation(doc.ToString());
            }
          }
           
    }
}

The examples refer to a simple TestClass type:

namespace Sample
{
    public class TestClass
    {
        public string id { get; set; }
        public string SomeData { get; set; }
    }
}

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.
CollectionName The name of the collection in the database being monitored by the trigger for changes.
ConnectionStringSetting The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account being monitored.
QueryString Defines the Mongo query expression used by the input binding return documents from the database. The query supports binding parameters.

Usage

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());
    }
}