azureentityazure-cosmosdbprimary-keyprimary-key-design

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?


Solution

  • 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.