通过MongoDB C#驱动程序的多个过滤器

时间:2015-06-09 07:37:55

标签: c# mongodb mongodb-.net-driver

运行时如何使用official drivers生成过滤器?我希望获取包含特定用户ID的联系人,并且可以针对某些属性(包含一些文本)进行过滤

当前代码不适用于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 个答案:

答案 0 :(得分:4)

使用以下代码检查生成的过滤器,并在其他地方发现错误

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