Creating a mongodb query in Java with $or and $in

人走茶凉 提交于 2019-12-07 04:56:41

问题


I am trying to write a java code using mongodb api to create this mongodb query:

{ "$or": [{"prd" : {"$in" : ["1234", "0987"]}} , {"rsin" : "3228742"}]}

Here's the code I am working with so far:

QueryBuilder builder = new QueryBuilder();

if (builder == null) {
    builder = QueryBuilder.start();
 }

if (mongoKey.equals("prd")){

     ArrayList<String> vals = new ArrayList<String>();

     for (int i=0; i < prdList; i++){
         vals.add(prdList.get(i));
     }

     DBObject obj = new BasicDBObject (mongoKey, new BasicDBObject("$in", vals));
     builder.or(obj);

}else {
      builder.and(mongoKey).is(mongoValue);
}

This is currently printing out the wrong syntax:

{ "$or": [{"prd" : {"$in" : ["1234", "0987"]}}] , "rsin" : "3228742"}

Any help?


回答1:


The problem is on else block, you need to use or method instead of and.

...
}else {
    builder.or(new BasicDBObject(mongoKey, mongoValue));
}

This will produce the query that you want.



来源:https://stackoverflow.com/questions/17561587/creating-a-mongodb-query-in-java-with-or-and-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!