Multiple filters via MongoDB C# driver

5.3k views Asked by At

How runtime generate filters with official drivers? I want get contacts that contains specific user id and can be filtered for some properties (contains some text)

Current code dont work with request.Filter > 1:

private FilterDefinition<Contact> BuildFilter(NgTableRequest request, string userId)
{
    var filters = new List<FilterDefinition<Contact>>
    {
        Builders<Contact>.Filter.Where(q => q.ContactUsers.Any(w => w.UserId == userId))
    };

    if (request.Filter != null && request.Filter.Any())
    {
        foreach (var reqFilter in request.Filter)
        {
            filters.Add(Builders<Contact>.Filter.Regex(reqFilter.Key, reqFilter.Value[0]));
        }
    }

    var result = Builders<Contact>.Filter.And(filters);

    return result;
}
1

There are 1 answers

0
offi On BEST ANSWER

Check generated filter using following code and found error in another place

    var documentSerializer = BsonSerializer.SerializerRegistry.GetSerializer<Contact>();
    var renderedFilter = result.Render(documentSerializer, BsonSerializer.SerializerRegistry).ToString();
    Trace.WriteLine("Filter: " + renderedFilter);