Guide to drop documents in Azure documentDB (new CosmosDB)

Several months ago, I started managing a non-relational DocumentDB database (new CosmosDB) on Azure. I had to delete some records, then I encountered some difficulties. The use of partitions and selecting the correct partition by ID was very important. So, I created the following Windows console application sample with c# which collects the document IDs based on a query and then deletes the documents for these IDs.

Initially we install the libraries Microsoft.Azure.DocumentDB and Newtonsoft.Json.

libraries.png

In order to connect the DocumentDB database with the Windows console application, you need the credentials (uri + primary key), which are on the “keys” Tab on Azure.

Untitled-1

Next, you initialize the documentDB uri, primary key, name of the collection and the name of the database.

private const string connectionEndpointUri ="https://dropdocuments.documents.azure.com:443/";
private const string primaryKey = "Kl9XbLDeSPjcmoJra7tKkHblfamvhmxFdzcw7LN3Pl44ENCdBYHax6krgmqGgqfpRbUEj73Rml0YAOR2ALJBZg==";
private static string databaseId = @"DatabaseName";
private static string collectionId = @"CollectionName";
private Uri collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);

Also, initialize the DocumentClient which provide a client-side representation for the Azure DocumentDB service.

private static DocumentClient client;

For this tutorial we want to retrieve all the keys, so we will run the query  “Select f.id from f”. It is important to define the partition. If you have not defined a partition in your DocumentDB database you can use this value “Undefined.Value”  in the FeedOptions for the field of partitionKey otherwise use the name of the key that you have in your database.

List<string> documentIds = await CollectIdsAsync();
public async static Task<List<string>> CollectIdsAsync()
{
    List<string> documentIds = new List<string>();

    FeedOptions feedOptions = new FeedOptions();
    feedOptions.PartitionKey = new PartitionKey("yourpartitionkey");

    using (client = new DocumentClient(new Uri(connectionEndpointUri), primaryKey))
    {
        Uri collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
        var query = client.CreateDocumentQuery(collectionLink, "Select f.id From f", feedOptions).AsDocumentQuery();
        while (query.HasMoreResults)
            foreach (var item in await query.ExecuteNextAsync())
                documentIds.Add(Convert.ToString((object)item));
    }
    return documentIds;
}

After you collect the document ids, you have to delete these documents from the documentDB on Azure.

client = null;
public class ResponseID
{
    public string id { get; set; }
}
foreach (string id in documentIds)
    await DeleteDocumentAsync(JsonConvert.DeserializeObject<ResponseID>(id).id);
public static async Task DeleteDocumentAsync(string id)
{
    Document doc = GetDocument(id);

    RequestOptions requestOptions = new RequestOptions();
    requestOptions.PartitionKey = new PartitionKey("yourpartitionkey");

    await Client.DeleteDocumentAsync(doc.SelfLink, requestOptions);
}
private static DocumentClient Client
{
    get
    {
        if (client == null)
        {
            string endpoint = connectionEndpointUri;
            string authKey = primaryKey;
            Uri endpointUri = new Uri(endpoint);
            client = new DocumentClient(endpointUri, authKey);
        }
        return client;
    }
}
private static Document GetDocument(string id)
{
    FeedOptions feedOptions = new FeedOptions();
    feedOptions.PartitionKey = new PartitionKey("yourpartitionkey");

    return Client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), feedOptions)
        .Where(d => d.Id == id)
        .AsEnumerable()
        .FirstOrDefault();
}

You can find this sample and download it from github to this link https://github.com/gntakakis/AzureDocumentDBDropDocuments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s