CosmosDB Get Scalar Value in C# using CosmosClient

Viewed 843

Does anyone know how to get a scalar value using the Microsoft.Azure.Comos.CosmosClient?

I have looked through the web and cannot find any examples.

All I want to do is to be able to execute a query like this

SELECT value COUNT(c._id) 
FROM c 
WHERE c._ts > @timestamp

There doesn't seem to get any function on either the CosmosClient or the Container classes to handle the type of query.

Thanks

2 Answers

You could do the following:

var container = client.GetContainer("test", "test");
var qry = container.GetItemQueryIterator<int>("SELECT VALUE COUNT(1) FROM c");
int count;
while (qry.HasMoreResults)
{
    count = (await qry.ReadNextAsync()).SingleOrDefault();
}

It works because you get an json integer array back from the Cosmos REST API. The SDK does a JsonConvert.Deserialize<int> (or similar) on it and you know the result of that is the single value you asked for.

There might be a better way, but I haven't seen any scalar method in v3 either.

var count = await _CosmosClient.GetCosmosContainer(CollectionName).
                          GetItemLinqQueryable<int>
                          ().CountAsync();

return count;

That is what I do to return the count. However, I am still wondering if there is any looping going on behind the scene. I wish I just had a method in which I could return the count.

Can anyone explain what is difference between the solution that I have and the privous one count = (await qry.ReadNextAsync()).SingleOrDefault();

Related