How to create a auto incremented column in Documentdb
14,556
DocumentDB doesn't include auto-increment functionality out of the box.
As Gaurav mentioned in Do we have Identity Column in DocumentDB, the id
field is special in that if a value isn't provided by the application - DocumentDB will assign a GUID automatically.
If you need the auto-increment functionality, one potential solution would be to store a counter as a document and leverage DocumentDB's triggers to populate your field and update the counter.
Related videos on Youtube
Author by
satish kumar V
Updated on June 04, 2022Comments
-
satish kumar V about 2 years
I want to create a document in azure documentdb with an auto-increment column.
Is this possible? If yes, please guide me.
Any help would be greatly appreciated.
Database db = CreateOrReadDocumentDb("EmployeeDb").Result; DocumentCollection dc = CreateOrReadDocumentCollection(db.SelfLink, "EmployeeDetails").Result; Employee emp = new Employee(); emp.Name="ABC"; emp.id="";//automatically generate a unique string emp.sal=10000; emp.exp =5; emp.index=0; // I want an auto increment column for emp with name index and want to store in azure document db client.CreateDocumentAsync(collectionLink, data);
-
Bernhard Koenig over 9 yearsA solution with triggers and a counter document would only work within the boundaries of a single collection. If you want to scale-out later and partition the data over multiple collections, this will become tricky. Just something one should think about before considering this solution. Of course, within a single collection, aliuy's solution is fine.
-
dwhieb over 8 yearsIt seems that there's no access to the collection object inside a trigger, so this unfortunately doesn't work.
-
Andrew Liu over 8 yearsYou can access the collection object inside a trigger via
getContext().getCollection()
. Here's an example: github.com/Azure/azure-documentdb-js-server/blob/master/samples/…