Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you build complex queries with MongoDB and the C# Driver?

Tags:

c#

mongodb

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.

like image 353
JustinN Avatar asked Aug 23 '12 11:08

JustinN


People also ask

How do I create a complex query in MongoDB?

Write an AND query. To write a compound query in MongoDB that matches all of the query predicates (i.e. a logical AND), specify all of the fields that you wish to match in your find document. By default, MongoDB matches all of the fields.

Is MongoDB good for complex queries?

As your queries are complex, SQL is the way to go. MongoDB is what's known as a NoSQL database. It is very fast, however it sacrifices robustness and has weak relational guarantees. Contrasting, SQL is resistant to outages and guarantees consistency between queries.

Can we write queries in MongoDB?

MongoDB queries provide the simplicity in process of fetching data from the database, it's similar to SQL queries in SQL Database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database.


1 Answers

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.

like image 117
Craig Wilson Avatar answered Oct 01 '22 19:10

Craig Wilson