Jordi
Jordi

Reputation: 23277

Spring data mongo: Build and criteria over same field

I've written this code in order to build this criteria:

Criteria filterCriteria = Criteria.where("application").is(applicationId);
if (null != from) {
    filterCriteria = filterCriteria
        .and("timestamp").gte(from);
}
if (null != to) {
    filterCriteria = filterCriteria
        .and("timestamp").lte(to);
}

I'm getting this exception message:

Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'timestamp' expression specified as 'timestamp : Document{{$lte=Sat Oct 10 00:00:00 CEST 2020}}'. Criteria already contains 'timestamp : Document{{$gte=Wed Oct 10 00:00:00 CEST 2018}}'.

Any ideas?

Upvotes: 2

Views: 233

Answers (1)

Mark B
Mark B

Reputation: 201048

You have to add both the gte and lte on a single and operation. This is how I'm doing a very similar query:

if (from != null && to != null) {
    criteria = criteria.and("timestamp").gte(from).lte(to)
}
else if (from != null) {
    criteria = criteria.and("timestamp").gte(from)
}
else if (to != null) {
    criteria = criteria.and("timestamp").lte(to)
}

Upvotes: 1

Related Questions