MongoDB query across multiple fields

I store some numbers in mongodb. For instance,

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

I want to find documents where, for example, if I pass "7", the request should check if 7 is between num1 and num2 and should return this document to me.

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 do not return me any result. Could you tell me the correct request for my purpose?

+4
source share
1 answer

You forgot to add $ to the operators. And I also suggest using 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 always no more than num2 .

+6
source

Source: https://habr.com/ru/post/1494814/


All Articles