Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo C# driver 2.0 - Find count without fetching documents

A general count query will be doing a

int count = collection.Find(filter).Count();

Now that loads all the records as per the filter, so lets says I have 1 million records and out of those 0.5 million match my filter, so I'll have collection already filled with 0.5 documents. This is good enough if you want the documents, but what if you just want to know the count and not really need the documents, for memory sake.

Can I do something like this

int count = collection.Find(filter).SetLimit(1).Count();

This gives me the same count as the first expression, but I hope that the memory will not utilized as the first expression, help me to know the correct way to find the "count" without loading all documents. Thanks.

like image 771
Mr767267 Avatar asked Dec 24 '22 14:12

Mr767267


1 Answers

You need to use the explicit CountAsync method and not Find:

long result = await collection.CountAsync(Builders<Hamster>.Filter.Eq(_ => _.Name, "bar"));
like image 126
i3arnon Avatar answered Jan 11 '23 22:01

i3arnon