4

I need the number of documents stored in a collection in my Azure Cosmos Db database. How can I get the count using LINQ query on the IQueryable object?

docDbClient.CreateDocumentQuery<TResult>().Count()

If I do above, I am unable to follow it up with .AsDocumentQuery() method.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
aman
  • 127
  • 2
  • 6

3 Answers3

3

This is my async implementation (use Count, for the sync version):

var count = await DocumentClient.
            CreateDocumentQuery<T>(CreateCollectionUri(), CreateFeedOptions()).
            Where(predicate).
            CountAsync();

where predicate is Expression<Func<T, bool>>

Roni Fuchs
  • 271
  • 3
  • 5
3

Another way to acheive that is:

using Microsoft.Azure.Cosmos.Linq; // required for CountAsync()
//...
cosmosClient
    .GetContainer(databaseName, containerName)
    .GetItemLinqQueryable<MyRecord>(true)
    .Where(r => r.Name == "John")
    .Where(r => r.Status == MyRecordStatus.Approved)
    .CountAsync()
Martin Meeser
  • 2,784
  • 2
  • 28
  • 41
J.Wincewicz
  • 849
  • 12
  • 19
2

You can try to use the following code to count the number of documents in your collection.

client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

IQueryable<int> total = client.CreateDocumentQuery<int>(UriFactory.CreateDocumentCollectionUri("testdb", "testcoll"), "SELECT Value count(1) FROM c", new FeedOptions() { EnableCrossPartitionQuery = true });

Console.WriteLine("total: " + total.AsEnumerable().FirstOrDefault());

Query result:

enter image description here

If you capture the request (using fiddler etc), you will find that the client sdk send the same query {"query":"SELECT VALUE [{\"item\": Count(1)}]\r\nFROM root"} to the server when you execute your code docDbClient.CreateDocumentQuery<TResult>().Count().

Community
  • 1
  • 1
Fei Han
  • 26,415
  • 1
  • 30
  • 41