Documentdb 简明教程
DocumentDB - Delete Document
在本章中,我们将学习如何从您的 DocumentDB 帐户中删除文档。使用 Azure 门户后,您可以通过在 Document Explorer 中打开文档并单击“删除”选项,轻松删除任何文档。
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.


它会显示确认消息。现在,按下“是”按钮,您将看到 DocumentDB 帐户中不再有该文档。
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.
现在,当您想使用 .Net SDK 删除文档时。
Now when you want to delete a document using .Net SDK.
Step 1 − 它与我们之前看到过的模式相同,我们将在其中首先查询以获得每个新文档的 SelfLinks。我们此处不使用 SELECT *,它将返回文档的全部内容,而这是我们不需要的。
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 − 相反,我们仅将 SelfLinks 选择到列表中,然后我们每次仅对一个 SelfLink 调用 DeleteDocumentAsync,以从集合中删除文档。
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();
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。
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 c.id =
'myfirstdb'").AsEnumerable().First();
collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
"SELECT * FROM c WHERE c.id = '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