我的应用程序通过QueryBuilder动态生成mongo查询。我试图这样做,以便传递的文本可以与我的集合中的几个字段进行比较。我需要遍历数据才能知道要添加到$ OR的内容(' text_to_compare' vs title字段,' text_to_compare vs body字段),所以我一直试图存储BasicDBList中$ OR子句的每个部分如下:
BasicDBObject orsDBObject = new BasicDBObject();
BasicDBList orsList = new BasicDBList();
for( String dbFieldNameInstance: listDBFieldName ){
QueryBuilder innerQB = new QueryBuilder();
innerQB.put(dbFieldNameInstance).is(obj.getValue()); //using this inner QueryBuilder to assist in creating the document
orsList.add(innerQB.get());
}
orsDBObject.putAll(orsList); //put each of the BasicDBList items into a BasicDBObject
qb.or(orsDBObject); //finally, add the entire $OR clause to my bigger querybuilder
System.out.println("qb: " + qb.get());
似乎我可能会跳过比必要更多的转化。它也不起作用。上面的输出最终看起来像这样:
qb:{" $或" :[{" 0" :{" primary_industries_names" :"电气"}," 1" :{" primary_industries_aliases" :"电气"}," 2" :{" secondary_industries_names" :"电气"}," 3" :{" secondary_industries_aliases" :"电气"}," 4" :{" product_experience_names" :"电气"}," 5" :{" product_experience_aliases" :"电气"}}]}
在大多数情况下,它看起来对我来说,但我不认为" 0":应该出现在那里。任何建议都将不胜感激。
答案 0 :(得分:0)
你有这种错误的方式。不重写你的代码,但你应该得到这个想法:
// Before the loop
QueryBuilder qb = new QueryBuilder();
// And loop things like this
for ( ) {
qb.or(new BasicDBObject("this","that"));
}
// After loop
System.out.println(qb.get());
如果您尝试嵌套多个条件,那么您似乎错过了$and
运算符。请考虑以下事项:
QueryBuilder qb = new QueryBuilder();
for (int x=0; x<2;x++) {
qb.or(new BasicDBObject("this","that"));
}
QueryBuilder qb2 = new QueryBuilder();
qb2.and(qb.get());
QueryBuilder qb3 = new QueryBuilder();
for (int x=0; x<2;x++) {
qb3.or(new BasicDBObject("something", "else"));
}
qb2.and(qb3.get());
System.out.println(qb2.get());