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.
You need to use the explicit CountAsync
method and not Find
:
long result = await collection.CountAsync(Builders<Hamster>.Filter.Eq(_ => _.Name, "bar"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With