Skip to main content

How to Change Only Some Properties of an Azure Cosmos DB Item with PatchItemAsync in C#

· 14 min read
Jagdish Kumawat
Founder @ Dewiride

PatchItemAsync changes only the properties you name in an Azure Cosmos DB item: your app sends the changes, and Cosmos DB applies them to the stored item. Here one call lowers a product's price, takes three pens off its stock and adds a tag, in a small C# app, with what Cosmos DB answered.

The usual way to change an item is to read it, change it in your code and write all of it back with ReplaceItemAsync. Microsoft's overview of partial document update describes that round trip: to update a document, the client needs to read it, execute Optimistic Concurrency Control checks (if necessary), update the document locally, and then send it over the wire as a whole document Replace API call. With a patch, the client can only send the modified properties/fields in a document without doing a full document replace operation. In the .NET SDK, that's PatchItemAsync and a list of PatchOperations.

Syntax​

Syntax
ItemResponse<<Type>> <response> = await <container>.PatchItemAsync<<Type>>(
"<id>",
new PartitionKey("<partition-key-value>"),
[
<operation>,
<operation>,
]);
PartWhat it is
<Type>The C# type the patched item is read back into
<container>The Container from CosmosClient.GetContainer
<id>The item's id
<partition-key-value>The item's partition key value. A patch changes one item, found by its ID and its partition key
PatchItemAsyncPatches an item in the Azure Cosmos service as an asynchronous operation. It takes the operations as an IReadOnlyList<PatchOperation>, and the patch operations are atomic and are executed sequentially
<operation>One change, made with a PatchOperation method from the table below. Microsoft's limit for one item: The maximum limit is 10 operations.
<response>.ResourceThe item after the patch: by default, resource body will be returned as part of the response

Each operation names a path and, for most of them, a value:

OperationWhat it does
PatchOperation.Set("<path>", <value>)Sets the value at the path, and adds the property if it doesn't exist
PatchOperation.Add("<path>", <value>)Adds the property, or replaces its value if it exists. With an array index, it inserts an element there, and with - instead of an index, it appends one to the end
PatchOperation.Replace("<path>", <value>)Like Set, but only for a property that exists. The SDK's reference: If the field is absent, Replace will fail and throw a 400 BadRequest
PatchOperation.Remove("<path>")Removes the property, or the array element at an index. A path that doesn't exist is an error
PatchOperation.Increment("<path>", <number>)Adds the number, a long or a double, to the value at the path. If the property doesn't exist, it's created with that number
PatchOperation.Move("<from>", "<path>")Removes the value at <from> and puts it at <path>

<path> is a JSON path in the stored item: /price for a top-level property, /inventory/quantity for one inside an object, /tags/0 for the first element of an array. It uses the property names of the item's JSON, not of your C# type. A name that contains / or ~ needs escaping: property names in paths need to escape the ~ and / characters as ~0 and ~1, respectively.

The Example​

A small shop keeps its products in a container products in the database howto, with the partition key path /id: every product is its own logical partition, so a product's partition key value is its ID. The console app ProductPatch stores a blue pen at 2.50 USD, 10 in stock, with the tag office. Then one patch sets the new price, 1.99, takes the three pens just sold off the stock, and adds the tag sale. It signs in with my Azure CLI account, and deletes the product at the end, so it can run again.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.
  • The Azure CLI, signed in with az login. The app uses that sign-in.
  • A Cosmos DB for NoSQL container whose partition key path is /id, and a Cosmos DB data role for your account on it, such as Cosmos DB Built-in Data Contributor: Connect using role-based access control and Microsoft Entra ID.

Step 1: Create a Console App and Add the Packages​

Terminal
dotnet new console -n ProductPatch
cd ProductPatch
dotnet add package Microsoft.Azure.Cosmos --version 3.64.0
dotnet add package Newtonsoft.Json --version 13.0.4
dotnet add package Azure.Identity --version 1.21.0

dotnet new console creates the project in a new folder ProductPatch, cd moves into it, and each dotnet add package adds one package at the version given. The last command ends with these lines:

Output (the last lines of the last command)
info : PackageReference for package 'Azure.Identity' version '1.21.0' added to file '/Users/you/source/ProductPatch/ProductPatch.csproj'.
info : Generating MSBuild file /Users/you/source/ProductPatch/obj/ProductPatch.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/ProductPatch/obj/project.assets.json
log : Restored /Users/you/source/ProductPatch/ProductPatch.csproj (in 862 ms).

The project file now references the three packages:

ProductPatch.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

</Project>

Microsoft.Azure.Cosmos is the Cosmos DB SDK, Newtonsoft.Json is a package the SDK requires you to reference yourself, and Azure.Identity has the Microsoft Entra ID credentials. How to Connect to Azure Cosmos DB with Microsoft Entra ID in C# explains each one and the client in detail.

Step 2: Connect​

Replace Program.cs, starting with the client:

Program.cs (the client)
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container products = client.GetContainer("howto", "products");
PartitionKey key = new("blue-pen");
  • AccountEndpoint is your account's URI, from its Overview page in the Azure portal.
  • AzureCliCredential signs in as the account you signed in with in the Azure CLI.
  • JsonSerializerOptions.Web writes property names in camelCase: Price is stored as price, Stock as stock and Tags as tags. Those stored names are the ones the patch paths use.
  • key is the product's partition key value. With the partition key path /id, it's the product's ID, blue-pen.

Step 3: Store a Product​

Program.cs (the product)
await products.UpsertItemAsync(new Product("blue-pen", "Blue pen", 2.50m, 10, ["office"]), key);
Product before = (await products.ReadItemAsync<Product>("blue-pen", key)).Resource;
Console.WriteLine($"Before: {Describe(before)}");

At the end of the file go the product's type and a helper that prints a product on one line:

Program.cs (the end of the file)
static string Describe(Product product) =>
$"{product.Name}, {product.Price:0.00} USD, {product.Stock} in stock, tags: {string.Join(", ", product.Tags)}";

record Product(string Id, string Name, decimal Price, int Stock, string[] Tags);
  • UpsertItemAsync creates the product, or replaces it if an earlier run left it behind.
  • ReadItemAsync reads it back, to show what's stored before the patch.
  • Product is a C# record. Its Id is stored as id, the name Cosmos DB requires, and Tags is an array, which a patch can append to.

Step 4: Patch Three Properties​

Program.cs (the patch)
// A new price, three pens sold and one more tag. Only these changes travel to Cosmos DB.
ItemResponse<Product> patched = await products.PatchItemAsync<Product>("blue-pen", key,
[
PatchOperation.Set("/price", 1.99m),
PatchOperation.Increment("/stock", -3),
PatchOperation.Add("/tags/-", "sale"),
]);
Console.WriteLine($"Patch: {(int)patched.StatusCode} {patched.StatusCode}, {patched.RequestCharge} RU");
Console.WriteLine($"After: {Describe(patched.Resource)}");
  • PatchOperation.Set("/price", 1.99m) sets the price. 1.99m is a C# decimal, the type of Price.
  • PatchOperation.Increment("/stock", -3) takes 3 off the stock. Microsoft's description of the operation: It can accept both positive and negative values. Cosmos DB does the sum on the stored value, so the app doesn't need to know the stock to record three sales.
  • PatchOperation.Add("/tags/-", "sale") appends sale to the tags array. In Microsoft's words: Instead of specifying an index, you can also use the - character. It also results in the element being appended to the array.
  • The square brackets are a C# collection expression: they build the IReadOnlyList<PatchOperation> that PatchItemAsync takes.
  • patched.Resource is the product after the patch, so the app prints it without reading it again.

The last statement before the helpers deletes the product, so the app can run again. How to Delete an Item by ID in Azure Cosmos DB with C# covers DeleteItemAsync.

Program.cs (clean up)
// Remove the product, so the app can run again.
await products.DeleteItemAsync<Product>("blue-pen", key);

Step 5: Run It​

Terminal
dotnet run
Output
Before: Blue pen, 2.50 USD, 10 in stock, tags: office
Patch: 200 OK, 11.99 RU
After: Blue pen, 1.99 USD, 7 in stock, tags: office, sale

macOS-style terminal window titled Terminal — ProductPatch showing dotnet run: Before, Blue pen at 2.50 USD with 10 in stock and the tag office; Patch, 200 OK for 11.99 RU; After, Blue pen at 1.99 USD with 7 in stock and the tags office and sale

  • Before: the product as stored, at 2.50 USD, with 10 in stock and one tag.
  • Patch: 200 OK, for 11.99 request units.
  • After: 1.99 USD, 7 in stock, and sale after office. The name, which no operation named, stayed as it was.

Don't expect a patch to cost much less than writing the whole item. Microsoft's FAQ on partial document update: Partial Document Update is normalized into request unit billing in the same way as other database operations. Users shouldn't expect a significant reduction in RU. What a patch saves is on your side, in Microsoft's words: Avoids extra CPU cycles on the client side, reduces end-to-end latency and network bandwidth.

The Complete File​

Program.cs
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container products = client.GetContainer("howto", "products");
PartitionKey key = new("blue-pen");

await products.UpsertItemAsync(new Product("blue-pen", "Blue pen", 2.50m, 10, ["office"]), key);
Product before = (await products.ReadItemAsync<Product>("blue-pen", key)).Resource;
Console.WriteLine($"Before: {Describe(before)}");

// A new price, three pens sold and one more tag. Only these changes travel to Cosmos DB.
ItemResponse<Product> patched = await products.PatchItemAsync<Product>("blue-pen", key,
[
PatchOperation.Set("/price", 1.99m),
PatchOperation.Increment("/stock", -3),
PatchOperation.Add("/tags/-", "sale"),
]);
Console.WriteLine($"Patch: {(int)patched.StatusCode} {patched.StatusCode}, {patched.RequestCharge} RU");
Console.WriteLine($"After: {Describe(patched.Resource)}");

// Remove the product, so the app can run again.
await products.DeleteItemAsync<Product>("blue-pen", key);

static string Describe(Product product) =>
$"{product.Name}, {product.Price:0.00} USD, {product.Stock} in stock, tags: {string.Join(", ", product.Tags)}";

record Product(string Id, string Name, decimal Price, int Stock, string[] Tags);

macOS-style code window titled Program.cs — ProductPatch showing a CosmosClient with AzureCliCredential, UpsertItemAsync and ReadItemAsync for the blue-pen product, then PatchItemAsync with three operations, PatchOperation.Set on /price with 1.99m, PatchOperation.Increment on /stock with -3 and PatchOperation.Add on /tags/- with sale, the status code and request charge printed, and DeleteItemAsync at the end

Common Mistakes​

MistakeWhat happensDo this instead
Expecting a patch to create a missing itemPatchItemAsync throws a CosmosException with the status NotFound (404)Create the item first with CreateItemAsync or UpsertItemAsync
Using Add with an array index to change an elementAdd inserts a new element at that index and shifts the others alongUse Set, which updates the element at that index
Using Replace for a property that may be missingIf the field is absent, Replace will fail and throw a 400 BadRequestUse Set, which adds a missing property
Patching _etag, _ts or another system propertySystem-generated properties like _id, _ts, _etag, _rid aren't modifiable using a patch operation.Patch only your own properties

Troubleshooting​

SymptomLikely causeFix
CosmosException with the status NotFound (404)No item with that ID in that partitionCheck the ID and the partition key value
The number of patch operations can't exceed 10.More than 10 operations in one callSplit the patch
Invalid patch request: check syntax of patch specification.The patch operation syntax is invalidCheck each operation and path against the tables in Syntax
CosmosException with the status BadRequest (400) from a ReplaceThe property doesn't exist in the itemUse Set, or check the path

FAQ​

What happens if the item doesn't exist?​

PatchItemAsync doesn't create it. In a separate run, I patched the ID no-such-product, which didn't exist: the call threw a CosmosException, and its status and request charge printed as 404 NotFound, 1 RU. To create an item that may be missing, write the whole item with UpsertItemAsync or CreateItemAsync.

Can I patch only when the item meets a condition?​

Yes, with a conditional patch: pass a PatchItemRequestOptions whose FilterPredicate holds the condition as requestOptions. Microsoft's example is FROM products p WHERE p.used = false, and the SDK's reference describes what happens: If the condition is satisfied the patch transaction will take place otherwise it will be returned with precondition failed. The example in this post doesn't use one.

Can a patch change the partition key?​

No. The SDK's reference for PatchItemAsync: The item's partition key value is immutable. To change an item's partition key value you must delete the original item and insert a new item. In this example the partition key path is /id, so the same goes for a product's ID.

Can I patch several items in one go?​

Yes, when they share a partition key value. Microsoft's overview: Multiple documents within the same partition key can be patched as a part of a transaction. In C#, that's a TransactionalBatch from CreateTransactionalBatch, with one PatchItem call per item, and Microsoft adds that if any operation fails, the entire transaction is rolled back. The example in this post patches a single item.

Conclusion​

To change a few properties of an Azure Cosmos DB item from C#, call PatchItemAsync with the item's ID, its partition key value and up to 10 PatchOperations: Set for a new value, Increment for a number, Add with - to append to an array, and Replace, Remove and Move for the rest. The paths use the names in the item's JSON, the operations apply in order and together, and the response holds the patched item.

Additional Resources​