如果我有以下架构-我如何找到有嘈杂动物的动物园?数据模型示例
public class Zoo
{
public List<Cage> Cages { get; set; }
}
public class Cage
{
public List<Animal> Animals { get; set; }
}
public abstract class Animal
{
public string Name { get; set; }
}
public class Feline : Animal
{
public int MeowsCount { get; set; }
}
public class Canine: Animal
{
public int BarksCount { get; set; }
}
现在我提取整个数据库,并找到必要的LINQ
public IEnumerable<Zoo> FindNoisyZoos(int soundsCount)
{
var allZoos = await zooCollection.Find(_ => true).ToListAsync();
List<Zoo> noisyZoos = allZoos.Where(z =>
z.Cages.Any(c =>
c.Animals.Where(a => ((Feline)a).MeowsCount == soundsCount || ((Canine)a).BarksCount == soundsCount))))
.ToList();
return noisyZoos;
}
这是非常低效的。我希望能够实现嵌套的ElemMatch,但是我不知道ElemMatch是如何工作的。我希望它是这样的:
public IEnumerable<Zoo> FindNoisyZoos(int soundsCount)
{
var noisyFelineFilter = new FilterDefinitionBuilder<Animal>().And(new FilterDefinitionBuilder<Animal>().OfType<Feline>(), new FilterDefinitionBuilder<Animal>().Eq(a => ((Feline)a).MeowsCount == soundsCount));
var noisyCanineFilter = new FilterDefinitionBuilder<Animal>().And(new FilterDefinitionBuilder<Animal>().OfType<Canine>(), new FilterDefinitionBuilder<Animal>().Eq(a => ((Canine)a).BarksCount == soundsCount));
var noisyAnimalFilter = new FilterDefinitionBuilder<Animal>().Or(noisyFelineFilter, noisyCanineFilter);
// smth like this: new FilterDefinitionBuilder<Zoo>().ElemMatch(z => z.Cages.ElemMatch(c => c.Animals.ElemMatch(noisyAnimalFilter)));
var noisyFilter;
var zoos = await zooCollection.Find(noisyFilter).ToListAsync();
return zoos;
}
MongoDB . net驱动程序可以在服务器端处理一些LINQ查询。它在底层将它们转换为MongoDB本地的。你试过zooCollection.AsQueriable().Where(z => z...).ToList()
之类的东西吗?.ToList()
最后到达,向客户端发送数据。如果它工作,过滤将在服务器端执行,如果它不工作,驱动程序将直接告诉你它不支持。