所以我有一个键值对列表,其中键是字符串,值是字符串数组,如下所示:
{
"filters": [
{"key": "team", "value": ["3","4","7"]},
{"key": "placement_type", "value": ["facility"]}
//{"key": "date", "value": ["2021-01-01"]}
//{"key": "policy", "value": ["something"]} Number of filters may vary
]
}
这个“过滤器”列表可以有多个键值对,具体取决于用户选择的过滤器数量。
所以我需要动态创建的是以下查询:
(builder.Eq("team", "3") | builder.Eq("team", "4") | builder.Eq("team", "7")) & builder.Eq("placement_type", "Facility");
这是我的尝试:
var builder = Builders<ReportDocument>.Filter;
// IF I USE THIS QUERY IT WORKS AS I EXPECT
var hardCodedQuery = (builder.Eq("team", "3") | builder.Eq("team", "4") | builder.Eq("team", "7")) & builder.Eq("placement_type", "Facility");
var dynamicQuery = builder.Empty;
var orFilters = builder.Empty;
foreach (var filter in request.Filters)
{
if (filter.Value.Length > 1)
{
for (int i = 0; i < filter.Value.Length; i++)
{
if (i == 0)
{
orFilters = builder.Eq(filter.Key, filter.Value[i]); //Had to do this since i have to initiate the variable as builder.Empty and it was adding and EmptyFilterDefinition
}
else
{
orFilters &= builder.Eq(filter.Key, filter.Value[i]);
}
}
dynamicQuery = builder.Or(orFilters);
}
else
{
dynamicQuery &= builder.Eq(filter.Key, filter.Value);
}
}
return await _reportsCollection.Find(dynamicQuery).ToListAsync();
但是一旦我在变量“orFilters”中插入第二个过滤器,操作符“&=”e就变成了MongoDB.Driver。AndFilterDefinition而不是 MongoDB.Driver。或过滤器定义
所以如果有人有好的方法,请分享给大家。我在 stackoverflow 中看到了很多类似我的问题,但都提到只使用 & (And) 运算符来做动态过滤器。但是因为我有一个字符串列表作为值,所以我需要使用 | (或)运算符也是如此。
谢谢