說我有一個典型的客戶和訂單場景。我有一組客戶,每個客戶文檔都有一個訂單清單。現在我想查詢訂單日期在上週內的客戶,即大於DateTime.UtcNow.AddDays(-7)並且小於DateTime.UtcNow。MongoDb c#Linq查詢並返回一個集合的子對象
var startDate = DateTime.UtcNow.AddDays(-7);
var endDate = DateTime.UtcNow;
var query = collection.AsQueryable<Customer>()
.Where(c => c.Orders.Any(o => o.OrderDate > startDate && o.OrderDate < endDate))
.SelectMany(b => b.Orders);
這將導致以下錯誤:
System.NotSupportedException: The SelectMany query operator is not supported.
at MongoDB.Driver.Linq.SelectQuery.TranslateMethodCall(MethodCallExpression methodCallExpression) in C:\\build\\mongo-csharp-driver\\Driver\\Linq\\Translators\\SelectQuery.cs:line 687
我目前的解決方案是非常討厭的:
var customers =
collection.AsQueryable<Customer>()
.Where(c =>
c.Orders.Any(o =>
o.OrderDate > startDate &&
o.OrderDate < endDate))
.ToList();
var results = new List<Order>();
foreach (var orders in customer.Select(c =>
c.Orders.Where(o =>
o.OrderDate > startDate &&
o.OrderDate < endDate)))
{
results.AddRange(orders);
}
return results;
有沒有更好的方式來實現這一目標?