简体   繁体   中英

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

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
}

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM