Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct IQueryable query using Linq when I just need count without reading all documents in Document-Db database?

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.

like image 451
aman Avatar asked Mar 09 '23 14:03

aman


2 Answers

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

like image 128
Roni Fuchs Avatar answered Apr 07 '23 01:04

Roni Fuchs


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()
like image 38
J.Wincewicz Avatar answered Apr 07 '23 03:04

J.Wincewicz