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

I developed a simple API that allows you to create an array of search criteria in the MongoDB collection. Now I should be able to convert this array into a real Mongo Query, and this part is where I am experiencing extreme difficulties.

Ideally, I get some syntax that will allow me to make 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); 

Actually, I want to create somewhat more complex queries, but in the end, after functionality, I dynamically build up my queries with objects, as shown in my pseudo-code above.

Feel free to ask me for additional details if I have not given myself a clear idea of ​​what I am trying to achieve.

+8
c # mongodb
source share
1 answer

It sounds like you have the right idea ... There is a class called Query, which is essentially a query builder without instantiating.

using MongoDB.Driver.Builders;

Query.And, Query.Or, etc. - everything is. This is the same as used under the linq provider to create complex queries.

+4
source share

All Articles