How to update existing documents in Cosmos DB using Azure Functions
New updates for 2024: A lot has changed with Azure Functions since this article was written. To view the latest recommendations, checkout this newer article I wrote for 2024 here.
Original article from 2022:
Azure Functions is one of my favourite Azure products thanks to its ease of use and its affordability, but there doesn’t seem to be clear docs on editing Cosmos DB documents. I needed this functionality for a feature I was building for my open-source UWP app called Ambie White Noise. So here’s a quick tutorial on how to do this via Visual Studio and C#.
Pre-requisites
- An existing Cosmos DB resource in Azure Portal with documents you want to edit
- An .NET Azure Function resource in Azure Portal
- Visual Studio 2022 (download)
Configuring your project
In Visual Studio, right click on the Connected Services
item in Solution Explorer and add a Cosmos DB service.
Follow the instructions to add your existing Cosmos DB resource to your Functions project.
Read documents via Azure Cosmos DB input binding
Create a function that uses Cosmos DB as input. Here’s an example.
This binding will instruct Azure Functions to connect to your Cosmos DB resource, run the given query, and provide the results as input to your function as the soundItems
parameter.
Edit documents via Azure Cosmos DB output binding
Now, to edit the documents, simply add an output binding like the screenshot below, and use the AddAsync
method indicated by the second green box.
This instructs your Azure Function to “add” the item to your database, but as long as your item has the same ID as an existing document, the AddAsync
operation will work more like an UpsertAsync
. This is something I discovered as I was experimenting with the output binding APIs.
So there you have it: an easy way to edit Cosmos DB documents via Azure Functions. Hope that works for you! Find me on twitter and let me know if you have any questions: https://twitter.com/kid_jenius.