Spring 数据 mongo:同一字段的构建和标准

Spring data mongo: Build and criteria over same field

我编写这段代码是为了建立这个标准:

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);
}

我收到此异常消息:

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}}'.

有什么想法吗?

您必须在单个 and 操作中同时添加 gtelte。这就是我做一个非常相似的查询的方式:

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)
}