How to set up a restriction on a specific item, making it unique in Cosmos DB?

Wei, Bella 0 Reputation points

Hi there,

I'm working on a REST API project that uses Java Spring Boot and Cosmos DB. I have multiple collections in this DB. This is the entity for one of the collections. I'd like to make one property unique, so no duplicate values can be inserted into this collection for the country property. For example, only a unique value can be inserted. If we have already inserted Japan, attempting to reinsert Japanwill result in an error.

Currently, I have set up both the partition key and unique key as country . This achieves the goal of preventing duplicate values from being inserted. However, I'm not sure if it's a good practice to set up a collection like this. Any suggestions?

private String id;

private String country;    // I want to make it unique, No duplicate value can be inserted
private String description;
private String createdBy;
private String updatedBy;

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,264 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sajeetharan 856 Reputation points Microsoft Employee

    Yes, your approach of having the partition key combined with the unique key guarantees the uniqueness of an item within the scope of the container.'

    Read more here

    0 comments No comments