Getting Started with Azure Cosmos DB, Part 2 – More Advanced Queries


| August 24, 2017 | in

Our first post covering Azure Cosmos DB was pretty basic. If you noticed, our READ query was always returning all results. So even if we wanted to find a single item, we had to return all of the items. That plan has obvious problems.

If we look at the code below, we can see that it returns all the records.

At least the code above disposes of the DocumentClient. 🙂

But how can we return just one record, especially if we know which one we want?

To read just one record we will make a few changes. First, we will call CreateDocumentUri to create the link.

Then we will call ReadDocumentAsync to read the document.

Here is the full code for the ReadOne method:


Now we had another method “Count” to our original work. To count the number of items we actually return all the items then count that. Wow that can be better; let’s make it better.

Our original code:

Now to return the count without returning all the data we will use the following. We basically have to just call Count on the document query.


But what if we want to page the data? Well we can do that too, but it gets a little more complicated. We will have to handle a RequestContinuation property and keep it between requests.

Here’s the code for a Page method that will return data in a paged format:

To call the above function, we will need a while statement where we keep reading until all the data has been returned (HasMore equals false).


Our first post in this series was intentionally basic. Now that we’re building on it, you should see a path to writing more completed queries using Azure Cosmos DB.

Related posts