Reputation: 15865
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
Upvotes: 6
Views: 8816
Reputation: 21
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;
Upvotes: 2
Reputation: 116558
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
}
Upvotes: 9
Reputation: 5773
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.
Upvotes: 2