How to do findAll in the new mongo C# driver and make it synchronous

Kar picture Kar · Apr 17, 2015 · Viewed 39.8k times · Source

I was using official C# driver to do a FindAll and upgraded to the new driver 2.0. FindAll is obsolete and is replaced with Find. I am trying to convert a simple method that returns me a list of Class1. Cant find a realistic example using a POCO in their documentation

var collection = database.GetCollection<ClassA>(Collection.MsgContentColName); return collection.FindAll().ToList();

Can someone please help me convert with 2.0 driver and return a list and not a task?

Answer

i3arnon picture i3arnon · Apr 18, 2015

EDIT:

They decided to add back synchronous support (although async is still preferable for IO operations) so you can simply use:

var list = collection.Find(_ => true).ToList();

Original:

Don't block synchronously on asynchronous code. It's bad for performance and could lead to deadlocks.

If you want to keep your application synchronous it's recommended that you keep using the old synchronous driver.

In the new v2.0 driver the async option should look like this:

async Task FooAsync()
{
    var list = await collection.Find(_ => true).ToListAsync();
}