MongoDB добавить запрос во время выполнения с драйвером C#> 2.0
Я хотел бы иметь возможность добавлять запросы во время выполнения. Мое решение со "старым" драйвером было таким.
// A List does hold the queries
List<IMongoQuery> QueryConditionList = new List<IMongoQuery>();
void AddQuery(string sType, string sField, string sValue)
{
// I can add of course several Queries
if (sType == "EQ")
QueryConditionList.Add(Query.EQ(sField, sValue));
else if (sType == "GT")
QueryConditionList.Add(Query.GT(sField, sValue));
else if (sType == "LT")
QueryConditionList.Add(Query.LT(sField, sValue));
}
// At some point you can execute the queries
void ExecuteQuery()
{
// Combine all to on "And" Query ("Or" would be possible as well)
IMongoQuery query = Query.And(QueryConditionList);
// Then I can get my cursor with a Find
MongoCursor<BsonDocument> mc = MoCollection.Find(query);
// Do anything with the cursor...
}
Это сработало довольно хорошо. Но я понятия не имею, как это сделать с новым синтаксисом. Все мои подходы не очень динамичны. Подобно:
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq(Field1, Value1) & builder.Eq(Field2, Value2);
Я думал, что мог бы добавить еще несколько фильтров, таких как
filter.add(builder.Eq(Field3, Value3)); // But of course I can't
1 ответ
Ниже описано, как это можно сделать с помощью нового API.
// A List does hold the queries
List<FilterDefition<BsonDocument>> QueryConditionList = new List<FilterDefition<BsonDocument>>();
void AddQuery(string sType, string sField, string sValue)
{
// I can add of course several Queries
if (sType == "EQ")
QueryConditionList.Add(Builders<BsonDocument>.Filter.Eq(sField, sValue));
else if (sType == "GT")
QueryConditionList.Add(Builders<BsonDocument>.Filter.Gt(sField, sValue));
else if (sType == "LT")
QueryConditionList.Add(Builders<BsonDocument>.Filter.Lt(sField, sValue));
}
Task ExecuteQueryAsync()
{
// The And method takes an IEnumerable<FilterDefinition<BsonDocument>>.
var filter = Builders<BsonDocument>.Filter.And(QueryConditionList);
var results = await MoCollection.Find(query).ToListAsync();
}