How to Change Only Some Properties of an Azure Cosmos DB Item with PatchItemAsync in C#
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
ItemResponse<<Type>> <response> = await <container>.PatchItemAsync<<Type>>(
"<id>",
new PartitionKey("<partition-key-value>"),
[
<operation>,
<operation>,
]);
| Part | What 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 |
PatchItemAsync | Patches 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>.Resource | The 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:
| Operation | What 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 --versionprints a version that starts with10.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
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:
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:
<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:
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");
AccountEndpointis your account's URI, from its Overview page in the Azure portal.AzureCliCredentialsigns in as the account you signed in with in the Azure CLI.JsonSerializerOptions.Webwrites property names in camelCase:Priceis stored asprice,StockasstockandTagsastags. Those stored names are the ones the patch paths use.keyis 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
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:
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);
UpsertItemAsynccreates the product, or replaces it if an earlier run left it behind.ReadItemAsyncreads it back, to show what's stored before the patch.Productis a C# record. ItsIdis stored asid, the name Cosmos DB requires, andTagsis an array, which a patch can append to.
Step 4: Patch Three Properties
// 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.99mis a C#decimal, the type ofPrice.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")appendssaleto thetagsarray. 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>thatPatchItemAsynctakes. patched.Resourceis 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.
// Remove the product, so the app can run again.
await products.DeleteItemAsync<Product>("blue-pen", key);
Step 5: Run It
dotnet run
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

- 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
saleafteroffice. 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
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);

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Expecting a patch to create a missing item | PatchItemAsync 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 element | Add inserts a new element at that index and shifts the others along | Use Set, which updates the element at that index |
Using Replace for a property that may be missing | If the field is absent, Replace will fail and throw a 400 BadRequest | Use Set, which adds a missing property |
Patching _etag, _ts or another system property | System-generated properties like _id, _ts, _etag, _rid aren't modifiable using a patch operation. | Patch only your own properties |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
CosmosException with the status NotFound (404) | No item with that ID in that partition | Check the ID and the partition key value |
| The number of patch operations can't exceed 10. | More than 10 operations in one call | Split the patch |
| Invalid patch request: check syntax of patch specification. | The patch operation syntax is invalid | Check each operation and path against the tables in Syntax |
CosmosException with the status BadRequest (400) from a Replace | The property doesn't exist in the item | Use 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
- Partial document update in Azure Cosmos DB — the six operations, the modes and the 10-operation limit.
- Get started with Azure Cosmos DB partial document update — .NET examples, the conditional patch and the common errors.
- Frequently asked questions about partial document update — request units, system properties and time to live.
- Container.PatchItemAsync — the method in the .NET SDK reference.
