[英]How to fetch data from mongoDB based on two dates in spring boot?
I'm using Aggregation in spring boot.我在 spring 引导中使用聚合。 but getting response as null
但得到响应为 null
Aggregation.match(Criteria.where("createdAt").lt(fromDate).gt(toDate));
mongoDbTemplate returning query as follows mongoDbTemplate 返回查询如下
"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}
so how to fetch data from MongoDB using mongoTemplate.aggregation.那么如何使用 mongoTemplate.aggregation 从 MongoDB 获取数据。 $date is not supported in mongo Shell, is there any solution for this?
mongo Shell 不支持 $date,有什么解决方案吗?
You need to use and
你需要使用
and
Aggregation.match(Criteria.where("createdAt").lt(fromDate)
.and("createdAt").gt(toDate));
Alternatively,或者,
Criteria
class has andOperator
function. Criteria
class 具有andOperator
。 You need to pass your conditions to that.你需要把你的条件传递给那个。
query.addCriteria(
new Criteria().andOperator(
Criteria.where("createdAt").lt(fromDate),
Criteria.where("createdAt").gt(toDate)
)
);
Another option is query annotation.另一种选择是查询注释。
@Query("{'createdAt': { $gte: ?0, $lte: ?1 } }")
Here, ?0
represents first argument to the function, $1
represents second argument to the function.这里,
?0
代表 function 的第一个参数, $1
代表 function 的第二个参数。
Try to understand the build-in methods you can create by functions names尝试了解您可以通过函数名称创建的内置方法
@Repository
public interface YourDTORepository extends MongoRepository<YourDTO, YourIdentifier> {
ArrayList<YourDTO> findByCreatedAtBetween(LocalDateTime from, LocalDateTime to);
}
Between expecting for two parameters and it will build the range for you.在期望两个参数之间,它将为您建立范围。
After lots of researh finally, I got the solution, probably this will help others.经过大量的研究,我终于找到了解决方案,这可能会对其他人有所帮助。
"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}
This is returned by mongoDbTemplate is right but it's not supporting the older version of spring boot.这由 mongoDbTemplate 返回是正确的,但它不支持旧版本的 spring 引导。
My project older version was我的项目旧版本是
<pom>
<groupId>com.Demo</groupId>
<artifactId>emp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
</pom>
I change it as follows我将其更改如下
<pom>
<groupId>com.Demo</groupId>
<artifactId>emp</artifactId>
<version>2.5.3</version>
<packaging>war</packaging>
</pom>
The rest of the code is the same as above.代码的rest同上。
So it's working fine.所以它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.