有没有一种方法可以在运行时在mongo查询中添加多个match语句?

时间:2019-05-03 10:23:07

标签: c# mongodb mongodb-query

我正在使用C#的Web API进行工作,如果一个JSON数组包含要在MongoDB查询的match子句中使用的某些数据,则会以这种形式从UI中获取输入。

我正在尝试使查询尽可能地动态,以便它与不同的集合以及要在运行时添加的任意数量的match语句一起使用,因为它将从JSON数组中一个接一个地检索它。

我尝试使用C#中可用的StringBuilder,但是由于字符串生成器返回了一个字符串,并且mongo-query必须是BsonDocument。

StringBuilder queryParam = new StringBuilder();
queryParam.Append("{\"" + item.Collection+"."+item.Key+"\""+ "new BsonDocument(){\"" + item.Collection + "." + item.Key + "\", new BsonDocument() { {\"$in\",  BsonArray.Create(" + item.Key + ")}}},");
var query = queryParam.ToString().Trim('"');

我尝试过的查询中的Match语句如下

{"$match", new BsonDocument(){
                            {item.Collection+"."+item.Key,query }}}

结果运行时,应构建为

{"$match, new BsonDocument(){{"<Value of item.Collection . "Value of item.Key",query }}}

现在,当循环再次在Json数组上运行时,我的match语句应为:

{"$match, new BsonDocument(){
{"<Value of item[1].Collection . "Value of item[1].Key",query },
{"<Value of item[2].Collection . "Value of item[2].Key",query }
}}

等等...

不好意思,如果这个问题很荒谬,我是MongoDB的新手。

0 个答案:

没有答案
相关问题