5

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?

1 Answer 1

7

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 .

Sign up to request clarification or add additional context in comments.

1 Comment

any idea on how to solve the same problem with Filters in mongo 3.3.0 and above?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.