Delete specific document from DocumentDb

2020-06-21 06:46发布

问题:

The following code retrieves all CrawlResult documents with a specific jobId.

var result = (from c in documentDb.CreateDocumentQuery<Shared.CrawlResult>(collection.SelfLink)
              where c.JobId == jobId
              select c);

Now I want to delete all documents with this specific jobId. The only way to delete documents I found was:

documentDb.DeleteDocumentAsync(string documentLink)

But how do I get the documentLink to execute the documentDb.DeleteDocumentAsync()?

回答1:

To do this, you need to write a SQL query so that you can dynamically access both the internal properties of Document, as well as CrawlResult.

For example, like in the following code:

class CrawlResult
{
    [JsonProperty("jobId")]
    public string JobId;
}

private async Task QueryAndDelete(DocumentClient client, string collectionLink)
{
    await client.CreateDocumentAsync(collectionLink, new CrawlResult { JobId = "J123" });
    await client.CreateDocumentAsync(collectionLink, new CrawlResult { JobId = "J456" });

    foreach (Document document in client.CreateDocumentQuery(
        collectionLink,
        new SqlQuerySpec(
            "SELECT * FROM crawlResults r WHERE r.jobId = @jobId",
            new SqlParameterCollection(new[] { new SqlParameter { Name = "@jobId", Value = "J123" } })
            )))
    {
        // Optionally, cast to CrawlResult using a dynamic cast
        CrawlResult result = (CrawlResult)(dynamic)document;

        await client.DeleteDocumentAsync(document.SelfLink);
    }
}


回答2:

Well, the official and efficient way is like follows:

  • First of all, you should create Client instance

    private static DocumentClient Client
    {
        get
        {
            if (client == null)
            {
                string endpoint = ConfigurationManager.AppSettings["endpoint"];
                string authKey = ConfigurationManager.AppSettings["authKey"];
                Uri endpointUri = new Uri(endpoint);
                client = new DocumentClient(endpointUri, authKey);
            }
            return client;
        }
    }
    
  • Next, you can reach the single document like this

    private static Document GetDocument(string id)
    {
        return Client.CreateDocumentQuery(Collection.DocumentsLink)
            .Where(d => d.Id == id)
            .AsEnumerable()
            .FirstOrDefault();
    }
    
  • Then you can do every CRUD operators. In this case, you can use this

    public static async Task DeleteAsync(string id)
    {
        Document doc = GetDocument(id);
        await Client.DeleteDocumentAsync(doc.SelfLink);
    }
    

To sum up, you can reach the document link after you get the Document instance. After that, you can find SelfLink attribute.

Cheers.



回答3:

Look like I am a little bit too late, but here're something I've been working with.

public async Task Delete(object key)
{
    var result = await _client.ReadDocumentAsync(UriFactory.CreateDocumentUri(dbName, nameof(TEntity), key as string));

    await _client.DeleteDocumentAsync(result.Resource.SelfLink);
}

Hope this help!



回答4:

One more possible way to delete a particular document is follows:

*) First you should create a Document client instance.

this.client = new DocumentClient(new Uri(m_ConnInfo.EndPointURL), m_ConnInfo.AccountKey);
Uri _docDbUri = new Uri("https://8878d4ed-0ee0-4-321-c9ef.documents.azure.com");
using (var client = new DocumentClient(_docDbUri, m_ConnInfo.AccountKey))
{
      try
      {
          var coll = client.CreateDocumentCollectionQuery(db.CollectionsLink).ToList().First();
          var docs = client.CreateDocumentQuery(coll.DocumentsLink);
          foreach (var doc in docs)
          {                       
               if (doc.Id == "123")
               {
                   client.DeleteDocumentAsync(doc.SelfLink).Wait();
               }      
          }
      }
      catch (Exception)
      {
           //ignored
      }
}

I hope this one should be more helpful for this question.