Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 979
night mare Avatar asked Oct 04 '22 14:10

night mare


1 Answers

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.

like image 68
Miguel Cartagena Avatar answered Oct 12 '22 12:10

Miguel Cartagena