How to do it...

Perform the following steps:

  1. Navigate to the Cosmos DB Account and click on the Add Azure Function menu in the All settings blade of the Cosmos DB account.
  1. You will be taken to the Add Azure Function blade, where you will choose the Azure function app in which you would like to create a new function (Cosmos DB trigger). This will be triggered whenever a change in the collection happens. Here is what it looks like:

  1. Once you have reviewed the details, click on the Save button (shown in the previous screenshot) to create the new function, which will be triggered for every change that is made in the collection. Let's quickly navigate to the Azure function app (in my case, it is AzureFunctionCookBookV2) and see whether the new function with the name cookbookdatacollectionTrigger has been created. Here is a view of my function app:

  1. Replace the default code with the following code of the Azure Functions Cosmos DB trigger, which gets a list of all the documents that were updated. The following code just prints the count of documents that were updated and the id of the first document in the Logs console:
#r "Microsoft.Azure.DocumentDB.Core"
using System;
using System.Collections.Generic;
using Microsoft.Azure.Documents;

public static void Run(IReadOnlyList<Document> input, ILogger log)
{
if (input != null && input.Count > 0)
{
log.LogInformation("Documents modified " + input.Count);
log.LogInformation("First document Id " + input[0].Id);
}
}
  1. Now, the integration of the Cosmos DB collection and the Azure Function is complete. Let's add a new document to the collection and see how the trigger gets fired in action. Open a new tab (leaving the cookbookdatacollectionTrigger tab open in the browser), navigate to the collection, and create a new document by clicking on the New Document button, as shown in the following screenshot:

  1. Once you have replaced the default JSON (which just has an id attribute) with the JSON that has the required attributes, click on the Save button to save the changes and quickly navigate to the other browser tab, where you have the Azure Function open, and view the logs to see the output of the function. The following is how my logs look, as I just added a value to the id attribute of the document. It might look different for you, depending on your JSON structure: