Search code examples
c#.netmongodbmongodb-.net-drivermongodb-csharp-2.0

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.


Solution

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

    long result = await collection.CountAsync(Builders<Hamster>.Filter.Eq(_ => _.Name, "bar"));