Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 612
horatius Avatar asked Mar 19 '18 06:03

horatius


2 Answers

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

 Document created = await client.CreateDocumentAsync(collectionLink, order);
like image 190
Sajeetharan Avatar answered Oct 21 '22 16:10

Sajeetharan


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.

like image 29
Jay Gong Avatar answered Oct 21 '22 17:10

Jay Gong