Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices for Primary Key in DocumentDB

I'm developing a web site with azure DocumentDB. I need to create unique and short primary key.

Since there isn't available auto increment in documentDB is there any good way to handle this problem.

I expect the answer with best practice advices. Thank You

like image 894
Dehan Wjiesekara Avatar asked Nov 27 '25 10:11

Dehan Wjiesekara


2 Answers

The most common practice I've seen is to simply use a GUID assigned when you create the new document to be added/inserted. You can also specify the Indexing Policy. This can help support situations where you need to find a document based on other properties within those documents.

Creating a custom, composite key is also useful if you usually know exactly which document you want to retrieve. In this case its up to the individual application to determine the best way to create the composite value.

like image 102
BrentDaCodeMonkey Avatar answered Nov 29 '25 23:11

BrentDaCodeMonkey


I have a document class whose primary key is named as PrimaryKey

public class Document<T> : BaseDocument, IDocument<T>
    {
        [JsonProperty(PropertyName = "id")]
        public virtual T PrimaryKey { get; set; }
    }

Since the document db primary key is id (lower case mandatory), You can replace the id with JSONProperty of Newtonsoft.Json, which will automatically get serialized with the value of PrimaryKey in the name of id.

like image 32
Karthikeyan VK Avatar answered Nov 29 '25 23:11

Karthikeyan VK