Search code examples
c#asynchronousmongodb-csharp-2.0

Mongo DB C# Driver 2.0 Synchronous Count


I need to count items that match a filter using an older controller that hasn't been switched to async. We have an async answer on how to do this:

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

I also found an article Introducing the 2.0 .NET Driver on the MongodDb website that has a comment that seems to confirm that it is impossible:

  1. It's async only: That's true. There has been a trend for new APIs to be async only (e.g. Microsoft's HttpClient). In general async programming is easy and results in higher server throughput without requiring a large number of threads. We are considering whether we should also support a sync API, and while we have gotten some requests for it (yours included) in general users seem eager to use async programming.

Nonetheless, I would like to ask if there is a way to do this / a confirmation that it's impossible without making the controller method async (and all its helpers).


Solution

  • Since v2.2 of the driver there are synchronous overloads for all the async methods so you should use them instead of blocking on the async API. Doing that is less performant and may lead to deadlocks:

    long countOfItemsMatchingFilter = yourCollectionName.Count(yourFilterName);