13

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);
satish kumar V
  • 1,695
  • 6
  • 33
  • 47

1 Answers1

11

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.

Andrew Liu
  • 8,045
  • 38
  • 47
  • 2
    A 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. – Bernhard Koenig Jan 19 '15 at 18:08
  • It seems that there's no access to the collection object inside a trigger, so this unfortunately doesn't work. – dwhieb Jan 24 '16 at 07:54
  • You can access the collection object inside a trigger via `getContext().getCollection()`. Here's an example: https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/triggers/UpdateMetadata.js – Andrew Liu Jan 27 '16 at 18:35