0

I wonder how to build complex query using mongo driver. This is my query:

var builder = Builders<MongoNavFilter>.Filter;
var query = builder.Where(x => x.Link == link && x.SubLink == subLink);
if (some statement)
{
    var finalExpression = ...
    query = query & Builders<MongoNavFilter>.Filter.Where(finalExpression); 
}
if (onsale)
    query = query & Builders<MongoNavFilter>.Filter.Where(x => !(x.Promo == null && x.Promo == string.Empty));

var filters = _db.GetCollection<MongoNavFilter>("NavFilters").
                    Find(query).ToList();

With EF IQueryable this code is working fine, but I can't build correct query with mongo driver. Could anyone told me what am I doing wrong?

1
  • Please update your post with sample MongoDB documents. Also mention what do you mean by "can't build correct query?" what error do you get? Commented Mar 20, 2016 at 14:42

1 Answer 1

5

Knowing what the finalExpression is would help, in case the problem is there. In my opinion, there might be a problem with mongodb driver's translation of !(x.Promo == null && x.Promo == string.Empty)

Could you try the following code instead of yours and see if it will make a difference

var builder = Builders<MongoNavFilter>.Filter;
var query = builder.Eq(x => x.Link, link) & builder.Eq(x=> x.SubLink, subLink);
if (some statement)
{
    var finalExpression = ... // write this using the same syntax 
    query = query & filter; 
}
if (onsale)
    query = query & builder.Ne(x=>x.Promo, null) & builder.Ne(x=> x. Promo, string.Empty);

var filters = _db.GetCollection<MongoNavFilter>("NavFilters").
                Find(query).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.