简体   繁体   English

如何使用MongoDB和C#驱动程序构建复杂查询?

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

I have developed a simple API which allows you to build up an array of search criteria within a MongoDB Collection. 我开发了一个简单的API,允许您在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. 我现在需要能够将此数组转换为实际的Mongo查询,而这部分是我遇到极大困难的地方。

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. 如果我没有清楚地了解我想要实现的目标,请随时向我询问其他详细信息。

Seems like you have the right idea... There is a class called Query that is essentially a query builder without the instantiation. 好像你有正确的想法......有一个名为Query的类,它本质上是一个没有实例化的查询构建器。

using MongoDB.Driver.Builders; 使用MongoDB.Driver.Builders;

Query.And, Query.Or, etc... are all there. Query.And,Query.Or等等都在那里。 It is the same thing that is used underneath the linq provider to build up complex queries. 在linq提供程序下面使用同样的东西来构建复杂的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM