DocumentDB - 删除文档

在本章中,我们将学习如何从DocumentDB帐户中删除文档.使用Azure门户,您可以通过在文档资源管理器中打开文档并单击"删除"选项轻松删除任何文档.

删除文档


删除文档对话框

它将显示确认消息.现在按是按钮,您将看到DocumentDB帐户中不再提供该文档.

现在,当您想使用.Net SDK删除文档时.

第1步 : 它与我们之前看到的模式相同,我们将首先查询每个新文档的SelfLink.我们这里不使用SELECT *,它会完整地返回我们不需要的文件.

第2步 : 相反,我们只是将SelfLinks选择到一个列表中,然后我们只为每个SelfLink调用DeleteDocumentAsync,一次一个,从集合中删除文档.

private async static Task DeleteDocuments(DocumentClient client) {
   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 =
      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);
   Console.WriteLine();
}

第3步 : 现在让我们从CreateDocumentClient任务调用上面的DeleteDocuments.

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 c.id =
         'myfirstdb'").AsEnumerable().First(); 
			
      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();  
			
      await DeleteDocuments(client); 
   } 
}

执行上述代码后,您将收到以下输出.

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