English 中文(简体)
DocumentDB - Delete Document
  • 时间:2024-09-17

DocumentDB - Delete Document


Previous Page Next Page  

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 cpck 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 pst 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(DocumentCpent cpent) {
   Console.WriteLine();
   Console.WriteLine(">>> Delete Documents <<<");
   Console.WriteLine();
   Console.WriteLine("Quering for documents to be deleted");
	
   var sql =
      "SELECT VALUE c._self FROM c WHERE STARTSWITH(c.name,  New Customer ) = true";
		
   var documentLinks =
      cpent.CreateDocumentQuery<string>(collection.SelfLink, sql).ToList();
		
   Console.WriteLine("Found {0} documents to be deleted", documentLinks.Count);

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

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

private static async Task CreateDocumentCpent() {
   // Create a new instance of the DocumentCpent 
   using (var cpent = new DocumentCpent(new Uri(EndpointUrl), AuthorizationKey)) {
      database = cpent.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
          myfirstdb ").AsEnumerable().First(); 
			
      collection = cpent.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id =  MyCollection ").AsEnumerable().First();  
			
      await DeleteDocuments(cpent); 
   } 
}

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 
Advertisements