C# script implementation for retrieving data from Cosmos DB through Azure function

The Bulk Executor library of Cosmos DB offers bulk operations such as inserts, updates, and deletes. To delete all documents, you can query them and then use a loop to delete each one by their corresponding ID obtained from the query.


To retrieve data, we can connect our Azure Functions to containers in Cosmos DB. This connection enables the Function to access data from the designated container during its execution.

If we have a Serverless API that relies on HTTP Triggers to call our Function, we can obtain a document from Azure Cosmos DB by utilizing an input binding.

Here’s a way that we could do it:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using GIBDemo.Core.Helpers;
using System.Collections.Generic;
using GIBDemo.Core.Models;
namespace GIBDemo.Triggers.Functions
    public static class ReadProductTrigger
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "ReadProduct/{id}")] HttpRequest req,
                databaseName: Constants.COSMOS_DB_DATABASE_NAME,
                collectionName: Constants.COSMOS_DB_CONTAINER_NAME,
                ConnectionStringSetting = Constants.COSMOS_DB_CONNECTION_STRING,
                SqlQuery ="SELECT * FROM c WHERE c.id={id} ORDER BY c._ts DESC")] IEnumerable productItem,
            ILogger log,
            string id)
            if (productItem == null)
                return new NotFoundResult();
            return new OkObjectResult(productItem);

For additional information on drawbacks and other approaches, refer to this link: https://towardsdatascience.com/working-with-azure-cosmos-db-in-your-azure-functions-cc4f0f98a44d.

Frequently Asked Questions

Posted in Uncategorized