Emil
Emil

Reputation: 423

Mongodb between query in java

i want to read all records that are between col1(value) and col2(value) in mongodb. so i write this code but it not work correctly. How implement this query?

my entity is : in my entity i suppose date as long because day or month no important for me.

private long id;
private String name;
private String description;
private long born_date ; // col1
private long death_date; // col2

all records between 200 and 500

      col1(val = 200)       col2(val = 500)
------|---------------------|------------

my code:

 Query betweenQuery = new Query();
    betweenQuery.addCriteria(Criteria.where("col1").gte(vla1)).
    addCriteria(Criteria.where("col2").lte(val2));
    return MongoOperations.find(betweenQuery , Entity.class);

Upvotes: 0

Views: 1798

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151132

As stated earlier, it does not make sense to split such a condition over two fields. Likely what you really want is that same condition on "both" fields:

    Query betweenQuery = new Query();
    betweenQuery.addCriteria(Criteria.where("col1").gte(200).lte(500)).
            addCriteria(Criteria.where("col2").gte(200).lte(500));

Serializes like this:

{ "col1" : { "$gte" : 200 , "$lte" : 500 } , "col2" : { "$gte" : 200 , "$lte" : 500 } }

So basically each column must contain values that are between those selected.

Also note that "BETWEEN" here is considered "inclusive", otherwise alter to $gt and $lt respectively

Upvotes: 1

Related Questions