Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you conditionally combine filters using the MongoDB C# driver?

Tags:

c#

mongodb

Consider the following filter:

var builder = Builders<Product>.Filter;

var filter = builder.Gte(i => i.Price, criteria.MinPrice) &
                            builder.Lte(i => i.Price, criteria.MaxPrice);
if (0 != criteria.CategoryId)
//Combine the following filter with the previous filter. How??
                var criteriaFilter = builder.Eq(i => i.CategoryId, criteria.CategoryId);

How do I combine the criteriaFilter and filter?

like image 603
bobbyalex Avatar asked Jun 01 '15 06:06

bobbyalex


1 Answers

if (criteria.CategoryId != 0)
{
    var criteriaFilter = builder.Eq(i => i.CategoryId, criteria.CategoryId);
    filter = filter & criteriaFilter;
}
like image 52
Sergey Berezovskiy Avatar answered Oct 20 '22 20:10

Sergey Berezovskiy