Mongo c#驱动程序-用嵌套动态构建过滤器

本文关键字:动态 构建 过滤器 嵌套 驱动程序 Mongo | 更新日期: 2023-09-27 18:10:05

假设有嵌套表达式

where a = 1 AND (b = 4 OR b = 5)

如何使用多个生成器对象和构建一个完整的过滤器出这样的表达式?

Mongo c#驱动程序-用嵌套动态构建过滤器

Builders是一个非常灵活的类,它也有覆盖的操作符"& = AND"and "| = OR"

你的例子将是

var filter = Builders<User>.Filter.Eq(x => x.A, "1");
filter &= (Builders<User>.Filter.Eq(x => x.B, "4") | Builders<User>.Filter.Eq(x => x.B, "5"));

如果您想有条件地添加更多过滤器,请使用此方法:

var builder = Builders<Student>.Filter;
var filter = builder.Empty;
if (!string.IsNullOrWhiteSpace(firstName))
{
   var firstNameFilter = builder.Eq(x => x.FirstName, firstName);
   filter &= firstNameFilter;
}
if (!string.IsNullOrWhiteSpace(lastName))
{
   var lastNameFilter = builder.Eq(x => x.LastName, lastName);
   filter &= lastNameFilter;
}
if (minAge != null && maxAge != null)
{
   var ageFilter = builder.And(builder.Gt(x => x.Age, minAge),
      builder.Lt(x => x.Age, maxAge));
   filter &= ageFilter;
}
var result = await _plpResultCollection.Find(filter).ToListAsync();

您可以像这样简单地使用.....

var filter = Builders<Rental>.Filter.Where(s => s._id== id && s.Price==1500);