Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting results from 2.0 MongoDb c# driver

I have built up a sample app using both the 1.0 and 2.0 c# drivers for MongoDb.

They serialize the same objects and I'm able to write with both and read from the 1.0. But I'm not able to use FindAsync in the 2.0 to give me any results.

Here is my 1.0 query that returns one document:

var results = collection.AsQueryable<FlatCatalogItem>()
                        .FirstOrDefault(c => c.BatchId == "2015.01.27" 
                                            && c.Upcs.Any(u => u.UPC == "123456803"));

My 2.0 query using the same data with the FindAsync looks like this:

var task = collection.FindAsync(item => item.BatchId == "2015.01.27" 
                                     && item.Upcs.Any(u => u.UPC == "123456803"));
task.Wait();
var results = task.Result;

The AsyncCursor that is returned from result has nothing in it.

results.MoveNextAsync().Wait(); // results.Current.Count = 0

This could be my ignorance with async and await, or perhaps I've missed something else with the 2.0 find methods? Note that I do not want to use the legacy 2.0 drivers

like image 433
crthompson Avatar asked Apr 02 '15 16:04

crthompson


3 Answers

The new API is async-only, you shouldn't block on it. It's not scalable and could possibly lead to deadlocks. Use async-await all the way or keep using the old API. In an async method the query should look like this:

async Task Foo()
{
    FlatCatalogItem first = await collection.
        Find(c => c.BatchId == "2015.01.27" && c.Upcs.Any(u => u.UPC == "123456803")).
        FirstOrDefaultAsync();

    // use first
}
like image 86
i3arnon Avatar answered Nov 15 '22 13:11

i3arnon


Can you please try this?

var task = collection.Find(item => item.BatchId == "2015.01.27" 
                                     && item.Upcs.Any(u => u.UPC == "123456803")).FirstOrDefaultAsync();

task.Wait();
var results = task.Result;

I trying to get used to the new API as well.

like image 42
D.Rosado Avatar answered Nov 15 '22 13:11

D.Rosado


Or perhaps a little more elegant:

var result = collection.Find(item => item.BatchId == "2015.01.27" 
                                  && item.Upcs.Any(u => u.UPC == "123456803"))
                       .FirstOrDefaultAsync().Result;
like image 34
Henrik Avatar answered Nov 15 '22 11:11

Henrik