Create a mongodb query in Java using $or $in

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

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

This is the code I have used 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 currently prints out the wrong syntax:

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

Does it help?

Solution

The problem is that on else blocks, you need to use or methods instead of and

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

This will generate the query you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>