Getting results from 2.0 MongoDb C # driver

I created a sample application using both 1.0 and 2.0 C # drivers for MongoDb.

They serialize the same objects, and I can write with them and read from 1.0. But I can not use FindAsync in 2.0 to give me any results.

Here is my 1.0 request, which returns a single document:

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

My query 2.0 using the same data with 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; 

AsyncCursor , which returns from the result, has nothing in it.

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

Could it be my ignorance with the async and wait, or maybe I missed something else using the 2.0 search methods? Please note that I do not want to use outdated version 2.0 .

+6
source share
3 answers

New async API - only you should not block it. It does not scale and can lead to deadlocks. Use async-await full or keep using the old API. In the async method, the request 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 } 
+9
source

Can you 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'm trying to get used to the new API.

+2
source

Or maybe a little more elegant:

 var result = collection.Find(item => item.BatchId == "2015.01.27" && item.Upcs.Any(u => u.UPC == "123456803")) .FirstOrDefaultAsync().Result; 
+2
source

Source: https://habr.com/ru/post/984626/


All Articles