假设我有一个典型的客户和订单场景。我有一个客户集合,每个客户文档都有一个订单列表。现在我要查询订单日期在上周的客户,即大于DateTime.UtcNow.AddDays(-7),小于DateTime.UtcNow。
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;
有没有更好的方法来实现这一目标?