Read Azure DocumentDB document that might not exist

Tuukka Haapaniemi picture Tuukka Haapaniemi · Feb 18, 2016 · Viewed 8.5k times · Source

I can query a single document from the Azure DocumentDB like this:

var response = await client.ReadDocumentAsync( documentUri );

If the document does not exist, this will throw a DocumentClientException. In my program I have a situation where the document may or may not exist. Is there any way to query for the document without using try-catch and without doing two round trips to the server, first to query for the document and second to retrieve the document should it exist?

Answer

Matias Quaranta picture Matias Quaranta · Feb 18, 2016

Sadly there is no other way, either you handle the exception or you make 2 calls, if you pick the second path, here is one performance-driven way of checking for document existence:

public bool ExistsDocument(string id)
{
    var client = new DocumentClient(DatabaseUri, DatabaseKey);
    var collectionUri = UriFactory.CreateDocumentCollectionUri("dbName", "collectioName");
    var query = client.CreateDocumentQuery<Microsoft.Azure.Documents.Document>(collectionUri, new FeedOptions() { MaxItemCount = 1 });
    return query.Where(x => x.Id == id).Select(x=>x.Id).AsEnumerable().Any(); //using Linq
}

The client should be shared among all your DB-accesing methods, but I created it there to have a auto-suficient example.

The new FeedOptions () {MaxItemCount = 1} will make sure the query will be optimized for 1 result (we don't really need more).

The Select(x=>x.Id) will make sure no other data is returned, if you don't specify it and the document exists, it will query and return all it's info.