DocumentDB - Delete Document

In this chapter, we will learn how to delete a document from your DocumentDB account. Using Azure Portal, you can easily delete any document by opening the document in Document Explorer and click the ‘Delete’ option.

Delete Document

Delete Document Dialog

It will display the confirmation message. Now press the Yes button and you will see that the document is no longer available in your DocumentDB account.

Now when you want to delete a document using .Net SDK.

Step 1 − It's the same pattern as we've seen before where we'll query first to get the SelfLinks of each new document. We don't use SELECT * here, which would return the documents in their entirety, which we don't need.

Step 2 − Instead we're just selecting the SelfLinks into a list and then we just call DeleteDocumentAsync for each SelfLink, one at a time, to delete the documents from the collection.

private async static Task DeleteDocuments(DocumentClient client) {
   Console.WriteLine(">>> Delete Documents <<<");
   Console.WriteLine("Quering for documents to be deleted");
   var sql =
      "SELECT VALUE c._self FROM c WHERE STARTSWITH(, 'New Customer') = true";
   var documentLinks =
      client.CreateDocumentQuery<string>(collection.SelfLink, sql).ToList();
   Console.WriteLine("Found {0} documents to be deleted", documentLinks.Count);

   foreach (var documentLink in documentLinks) {
      await client.DeleteDocumentAsync(documentLink);
   Console.WriteLine("Deleted {0} new customer documents", documentLinks.Count);

Step 3 − Now let’s call the above DeleteDocuments from the CreateDocumentClient task.

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient 
   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE =
      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE = 'MyCollection'").AsEnumerable().First();  
      await DeleteDocuments(client); 

When the above code is executed, you will receive the following output.

***** Delete Documents *****  
Quering for documents to be deleted 
Found 2 documents to be deleted 
Deleted 2 new customer documents