Friday, July 27, 2018

MongoDB with C#: finding elements with custom predicate

Pass Lambda expression as parameter to filter data from mongodb collection. 
Your data filter function could be

public IEnumerable<BsonDocument> FindAllWithPredicate(Func<BsonDocument, bool> condition)
{
    return Collection.AsQueryable().Where(condition).ToArray();
}

Predicatebuilder.cs

public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>()
    {
        return f => true;
    }

    public static Expression<Func<T, bool>> False<T>()
    {
        return f => false;
    }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
            (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
            (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}  
Generate lambda expression by predicate builder
public static class PredicateBuilderStore
{
    public static Func<BsonDocument, bool> GetPredicateForBsonDocument(Entity entity)
    {
        var predicate = PredicateBuilder.True<BsonDocument>();            
        predicate = predicate.And(d => d.GetElement({key}).Value == CompareWithValue);
        return predicate.Compile();
    }   
}
if you want to query just all items, you could do it as:

return this.collection.Find(_=>true).ToArray();

No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...