我在春季启动中使用聚合。但得到的响应为空
Aggregation.match(Criteria.where("createdAt").lt(fromDate).gt(toDate));
mongoDbTemplate返回如下的查询
"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}
那么如何使用mongoTemplate.aggregation从MongoDB中获取数据。mongo Shell不支持$date,有什么解决办法吗?
如果您想获得范围[从,到],则需要使用and
Aggregation.match(Criteria.where("createdAt").lt(fromDate)
.and("createdAt").gt(toDate));
或者,
Criteria
类具有andOperator
函数。你需要通过你的条件。
query.addCriteria(
new Criteria().andOperator(
Criteria.where("createdAt").lt(fromDate),
Criteria.where("createdAt").gt(toDate)
)
);
另一个选项是查询注释。
@Query("{'createdAt' : { $gte: ?0, $lte: ?1 } }")
这里,?0
表示函数的第一个自变量,?1
表示函数的第二个自变量。
参考
试着理解可以通过函数名创建的内置方法
@Repository
public interface YourDTORepository extends MongoRepository<YourDTO, YourIdentifier> {
ArrayList<YourDTO> findByCreatedAtBetween(LocalDateTime from, LocalDateTime to);
}
在期望两个参数之间,它将为您构建范围。
经过大量研究,我终于找到了解决方案,这可能会帮助其他人。
"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}
这是由mongoDbTemplate返回的。这是正确的,但它不支持旧版本的spring-boot。
我的项目旧版本是
<pom>
<groupId>com.Demo</groupId>
<artifactId>emp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
</pom>
我把它改成
<pom>
<groupId>com.Demo</groupId>
<artifactId>emp</artifactId>
<version>2.5.3</version>
<packaging>war</packaging>
</pom>
代码的其余部分与上述内容相同。
所以它运行得很好。