Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 428
Kar Avatar asked Apr 17 '15 21:04

Kar


2 Answers

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(); } 
like image 149
i3arnon Avatar answered Oct 02 '22 14:10

i3arnon


With the MongoDb version 2.2.4, the implementation changed a little bit. Following the best practices let's build the MongoDb connection like this:

public static class PatientDb {     public static IMongoCollection<Patient> Open()     {         var client = new MongoClient("mongodb://localhost");         var db = client.GetDatabase("PatientDb");         return db.GetCollection<Patient>("Patients");     }  } 

Now is returned a interface of IMongoCollection instead of instance of a concrete class like MongoCollection. There is no need of create a instance of server to get the database anymore, the client can reach the database directly.

Then in the controller is done like this:

public class PatientController : ApiController {     private readonly IMongoCollection<Patient> _patients;      public PatientController()     {         _patients = PatientDb.Open();     }     public IEnumerable<Patient> Get()     {         return _patients.Find(new BsonDocument()).ToEnumerable();     } } 

Where _patients is a IMongoCollection and to retrieve all Patients instead to use the FindAll() now is used the Find() where the filter is an new instance of BsonDocument.

like image 33
PedroSouki Avatar answered Oct 02 '22 16:10

PedroSouki