How can I retrieve the id of a document I added to a Cosmosdb collection?

4.9k Views Asked by At

I have a single collection into which I am inserting documents of different types. I use the type parameter to distinguish between different datatypes in the collection. When I am inserting a document, I have created an Id field for every document, but Cosmosdb has a built-in id field.

How can I insert a new document and retrieve the id of the created Document all in one query?

3

There are 3 best solutions below

0
Jay Gong On BEST ANSWER

I think you just need to .getResource() method to get the create document obj.

Please refer to the java code:

DocumentClient documentClient = new DocumentClient(END_POINT,
                    MASTER_KEY, ConnectionPolicy.GetDefault(),
                    ConsistencyLevel.Session);

Document document = new Document();
document.set("name","aaa");

document = documentClient.createDocument("dbs/db/colls/coll",document,null,false).getResource();

System.out.println(document.toString());

//then do your business logic with the document.....

C# code:

Parent p = new Parent
            {
                FamilyName = "Andersen.1",
                FirstName = "Andersen",
            };

Document doc = client.CreateDocumentAsync("dbs/db/colls/coll",p,null).Result.Resource;
Console.WriteLine(doc);

Hope it helps you.

1
Sajeetharan On

The CreateDocumentAsync method returns the created document so you should be able to get the document id.

 Document created = await client.CreateDocumentAsync(collectionLink, order);
1
Imre Pühvel On

Sure, you could always fetch the id from creation method response in your favorite API as already shown in other answers. You may have reasons why you want to delegate key-assigning to DocumentDB, but to be frank, I don't see any good ones.

If inserted document would have no id set DocumentDB would generate a GUID for you. There wouldn't be any notable difference compared to simply generating a new GUID yourself and assign it into id-field before save. Self-assigning the identity would let you simplify your code a bit and also let you use the identity not only after persisting but also BEFORE. Which could simplify a lot of scenarios you may have or run into in future.

Also, note that you don't have to use GUIDs as as id and could use any unique value you already have. Since you mentioned you have and Id field (which by name, I assume to be a primary key) then you should consider reusing this instead introducing another set of keys.

Self-assigned non-Guid key is usually a better choice since it can be designed to match your data and application needs better than a GUID. For example, in addition to being just unique, it may also be a natural key, narrower, human-readable, ordered, etc.