Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article explains how to work with the Azure Cosmos DB for MongoDB vCore output binding in Azure Functions.
The Azure Cosmos DB for MongoDB (vCore) output binding lets you write a new document to an Azure Cosmos DB for MongoDB(vCore) collection.
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 CosmosDBMongoCollector
to add an item to the database:
[FunctionName("OutputBindingSample")]
public static async Task OutputBindingRun(
[TimerTrigger("*/5 * * * * *")] TimerInfo myTimer,
[CosmosDBMongo("%vCoreDatabaseBinding%", "%vCoreCollectionBinding%", ConnectionStringSetting = "vCoreConnectionStringBinding")] IAsyncCollector<TestClass> CosmosDBMongoCollector,
ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
TestClass item = new TestClass()
{
id = Guid.NewGuid().ToString(),
SomeData = "some random data"
};
await CosmosDBMongoCollector.AddAsync(item);
}
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. |
CreateIfNotExists | (Optional) When set to true, creates the targeted database and collection when they don't already exist. |
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());
}
}