
If you want to create custom unique keys inside a collections, you can simply create a UniqueKeyPolicy while creating your collection.
1private static async Task CreateCollectionIfNotExistsAsync(string db, string collection, string keyName, string columnName)
2{
3 try
4 {
5 Uri link = UriFactory.CreateDocumentCollectionUri(db, collection);
6 await client.ReadDocumentCollectionAsync(link);
7 }
8 catch (DocumentClientException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound)
9 {
10 // Define Collection
11 DocumentCollection dc = new DocumentCollection();
12 dc.Id = collection;
13
14 // Set PK
15 dc.PartitionKey.Paths.Add("/" + keyName);
16 dc.UniqueKeyPolicy = new UniqueKeyPolicy
17 {
18 UniqueKeys =
19 new Collection<UniqueKey>
20 {
21 new UniqueKey { Paths = new Collection<string> { "/" + columnName}}
22 }
23 };
24
25 // Create Cllection
26 await client.CreateDocumentCollectionAsync(
27 UriFactory.CreateDatabaseUri(db),
28 dc,
29 new RequestOptions { OfferThroughput = 1000 });
30
31 }
Also you can enforce unqiue key policies to existing collection:
1private static async Task EnforceUniqueKeyPolicy(string db, string collection, string keyName, string columnName)
2{
3
4 UniqueKeyPolicy policy = new UniqueKeyPolicy
5 {
6 UniqueKeys =
7 new Collection<UniqueKey>
8 {
9 new UniqueKey { Paths = new Collection<string> { "/" + columnName }}
10 }
11 }
12
13 Uri link = UriFactory.CreateDocumentCollectionUri(db, collection);
14 DocumentCollection dc = client.ReadDocumentCollectionAsync(link);
15
16 dc.UniqueKeyPolicy = policy;
17
18 await client.ReplaceDocumentCollectionAsync(dc);
Related articles

Feb 26, 2026 · 6 min read
Run Azure Cosmos DB locally with .NET Aspire and make emulator endpoints visible in the dashboard
When building cloud-native .NET applications, two goals often matter at the same time: a fast local development loop and a clean path to …

Sep 24, 2025 · 9 min read
Automatically discover tools for Azure OpenAI Realtime API
Azure now provides a unified Realtime API for low‑latency, multimodal conversations over WebRTC or WebSockets. If you’ve used the earlier …

Sep 01, 2025 · 3 min read
Azure Document Intelligence – Fix: ContentSourceNotAccessible (Invalid data URL)
Problem Training custom models (for example, delivery notes) in Azure Document Intelligence initially worked fine. Suddenly, both training …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

Comments