9

I have developed a simple API which allows you to build up an array of search criteria within a MongoDB Collection. I now need to be able to convert this array into an actual Mongo Query, and this part is where I am having extreme difficulty.

Ideally I am after some syntax that will allow me to do the following pseudo code:

var query = new QueryBuilder();
foreach (var group in groups)
{
    switch (group.Condition)
    {
        case GroupCondition.Or:
            query.Or(group.Queries);
        break;
        case GroupCondition.And:
            query.And(group.Queries);
        break;
    }
}
return myCollection.FindAs(type, query);

I actually want to build up slightly more complex queries, but ultimately I am after the functionality to dynamically build up my queries with objects as seen in my pseudo code above.

Feel free to ask me for additional details if I have not made myself clear enough about what I am trying to achieve.

2
  • So before you get too far, you should look into using Linq. Commented Aug 23, 2012 at 23:09
  • Same here. I see a few people use examples of Query with multiple query expressions chained together however, when I do this like Query.EQ().GT(); it doesn't work as EQ/GT don't return a query object. What am I missing here? Commented Feb 27, 2014 at 19:51

1 Answer 1

4

Seems like you have the right idea... There is a class called Query that is essentially a query builder without the instantiation.

using MongoDB.Driver.Builders;

Query.And, Query.Or, etc... are all there. It is the same thing that is used underneath the linq provider to build up complex queries.

Sign up to request clarification or add additional context in comments.

3 Comments

Can somebody actually point at an example that shows multiple query selectors strung together? Looks like Query is not chainable.
@RickStrahl build it up like an AST. Query.And( Query.OR( Query.EQ("x", 1), Query.EQ("y", 2)), Query.GT("z", 3));
@RickStrahl I ended up making a bespoke Query Language which breaks down, and then compiles into Mongo Queries (hence asking this question). The Query Language got scrapped in the end, but it did work (with a number of tests!). Do you still need help? I've been tempted to re-create it and public as OSS - maybe even publish a NuGet package for some of the helpers.

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.