質問

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?

役に立ちましたか?

解決

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 .

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top