0

I have a collection, say, test which contains some 100 fields like _1, _2, _3 etc

Now I want to form MongoDB query such that whatever input comes like 1, 2, 5 or 5, 6, 7, 8, 9.

A proper query can be generated. Please help with respect to MongoJack.

Community
  • 1
  • 1
rohitanand
  • 710
  • 1
  • 4
  • 26
  • What did you try so far? – il_raffa Oct 13 '15 at 07:18
  • @il_raffa I created another field in collection which contains indices of all the (1 to 100 which has values in them) and tried in with the given input but it does not work as I expected. That's why posted the question. – rohitanand Oct 13 '15 at 07:23

2 Answers2

0

Try concatenating the input with the underscore character first then use the joined string in the query, something like:

StringBuilder sb = new StringBuilder();
sb.append("_");
sb.append(input);
String field = sb.toString();

List<Foo> bar = coll.find(DBQuery.is(field, "foo")).toArray();
chridam
  • 100,957
  • 23
  • 236
  • 235
  • I am not really sure if its going to work. I had already appended the input string but problem is to dynamically add fields in which to look for,,, _(field, "foo"))_ is this really correct? – rohitanand Oct 13 '15 at 08:19
  • Oh, you mean if the input came as a comma delimited string and you would want to create a query based on that, right? – chridam Oct 13 '15 at 08:23
  • Yes, it the input came as 1, 5, 8 then my query should be something like this DBQuery.and(DBQuery.is("_1", 1), DBQuery.is("_5", 5), DBQuery.is("_8", 8))); I require this to be dynamic – rohitanand Oct 13 '15 at 08:24
0

I have finally found the solution. We can do something like this :

Query q = DBQuery.empty();
for(int i=0; i < params.length ; i++ ) {    
    q = q.or(DBQuery.greaterThan("_"+(Integer.valueOf(params[i])+1), 0));
}

Worked for me

rohitanand
  • 710
  • 1
  • 4
  • 26