Purging Azure DocumentDB records without a PartitionKey

0
December 31, 2016 // documentdb

Lets say you’re using DocumentDB and find yourself migrating from single-partition to partitioned collections.

There’s an off chance you may forget to add a PartitionKey property value to all records before migration.  DocumentDB will allow you to create documents without a PartitionKey, but querying for them is a little more tricky.

With the help of Frans Lytzen’s article you’ll be able to Find docs with no PartitionKey in Azure DocumentDb.

To take things one step further, you may want to purge those records prior to re-running your import. If that’s the case, here’s an example of the code you may need:


        private static async Task<int> PurgeUnpartitionedDocuments(IDocumentClient client, Uri collectionUri)
        {
            var documentQuery = client.CreateDocumentQuery<Document>(collectionUri, new FeedOptions { PartitionKey = new PartitionKey(Undefined.Value) }).AsDocumentQuery();
            int count = 0;

            while (documentQuery.HasMoreResults)
            {
                foreach (Document document in await documentQuery.ExecuteNextAsync())
                {
                    await client.DeleteDocumentAsync(document.SelfLink, new RequestOptions { PartitionKey = new PartitionKey(Undefined.Value) });
                    count++;
                }
            }

            return count;
        }

Hope it helps! Thanks again to Frans for his very helpful article. 🙂

About the author

Steve Cadwallader is a software developer who geeks out on user interfaces, clean code and making things easier.

Leave a Comment