1

I would like to have the possibilitie to add queries at runtime. My Solution with the "old" driver was like this.

    // 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...
    }

This did work quite well. But I don't have a clue how to do it with the new syntax. All my approaches are not really dynamic. Like:

var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq(Field1, Value1) & builder.Eq(Field2, Value2);

I thought I could add some more filters like

filter.add(builder.Eq(Field3, Value3)); // But of course I  can't
U.Ho
  • 11
  • 3

1 Answers1

0

Below is how this can be done using the new 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();
}
Craig Wilson
  • 12,174
  • 3
  • 41
  • 45