Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB query on multiple fields

I am storing some numbers in mongodb. For e.g.

  • num1:5
  • num2:10
  • num1:11
  • num2:15

I want to find documents where for e.g. if I pass '7' the query should check if 7 lies between num1 and num2 and must return me this document.

I tried

BasicDBObject query = new BasicDBObject("num1", new BasicDBObject("gte", 7).append("num2",new BasicDBObject("lte", 7)));

and

List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
        obj.add(new BasicDBObject("num1", new BasicDBObject("gte", 7)));
        obj.add(new BasicDBObject("num2", new BasicDBObject("lte", 7)));
        query.put("$and", obj);

Both are not returning me the any result. Could you please let me know correct query for my purpose?

like image 995
koustubhC Avatar asked Aug 01 '13 19:08

koustubhC


1 Answers

You forgot to add $ to operators. And I also suggest to use QueryBuilder for this case, it is much more convenient:

DBObject query = QueryBuilder.start("num1").lessThanEquals(7).and("num2").greaterThanEquals(7).get();

I assume that num1 is always not greater than num2 .

like image 170
Alex P Avatar answered Sep 17 '22 12:09

Alex P