Documentdb 简明教程

DocumentDB - Delete Document

在本章中,我们将学习如何从您的 DocumentDB 帐户中删除文档。使用 Azure 门户后,您可以通过在 Document Explorer 中打开文档并单击“删除”选项,轻松删除任何文档。

delete document
delete document dialog

它会显示确认消息。现在,按下“是”按钮,您将看到 DocumentDB 帐户中不再有该文档。

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

Step 1 − 它与我们之前看到过的模式相同,我们将在其中首先查询以获得每个新文档的 SelfLinks。我们此处不使用 SELECT *,它将返回文档的全部内容,而这是我们不需要的。

Step 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();
}

Step 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