Search code examples
c#azure-cosmosdb

CosmosDB Get Scalar Value in C# using CosmosClient


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


Solution

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