How to Upload multiple Document (bulk) in Document DB

Pravin Sharma picture Pravin Sharma · Mar 17, 2016 · Viewed 9.8k times · Source

I have Documents list(object) that object has multiple documents i.e. Json records are present but while I try to upload that Bunches of Document(Records) it not upload on document DB but while I upload Single Document records it upload succesfully.

  List<MyModelClass> listObj = new List<MyModelClass>();
  Document doc = await DocumentClient.CreateDocumentAsync("dbs/" + DocumentDatabase.Id + "/colls/" + DocumentCollection.Id, listObj);

above code is not working.....

   foreach (var item in listObj )
    {
      Document doc = await Client.CreateDocumentAsync("dbs/" + DocumentDatabase.Id + "/colls/" + DocumentCollection.Id, item);
    }

This code is working for me.....

 Syntax : CreateDocumentAsync(String, Object, RequestOptions, Boolean)
 Object :- Document object // I Know it as per syntax it need to be "Document Type".

I want any Other way to Upload All Document at Once....

Answer

David Makogon picture David Makogon · Mar 17, 2016

You cannot insert more than one document at a time. The call to CreateDocumentAsync() is for single documents only.

To accomplish this, you'd need to devise some type of server-side stored procedure to accomplish this, and then pass your document array to the function in a single call. You may want to look at this answer to see how someone else solved this using a server-side function, by essentially creating an array of documents locally, and then walking through the array in their stored procedure. So, creating something like this (as excerpted from that answer):

docObject = {
  "items": [{doc}, {doc}, {doc}]
}

And passing docObject to your stored procedure.

Ultimately, your stored procedure would still be making individual insert calls, one per document. But... you would not have the multiple network round-trips. And the inserts would be transactional (if one of the inserts failed, or you threw an exception, the other inserts would be rolled back).