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

Don't Panic Labs
Aug 24, 2017 · 2 min read

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:

Count

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.

Paging

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).

Conclusion

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.


Written by Chad Michel and originally published at dontpaniclabs.com on August 24, 2017.

)

Don't Panic Labs

Written by

We enable sustainable business agility through our proven principles, processes, and patterns. Stay up to date with our newsletter: http://eepurl.com/bljc1P

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade