[英]How to configure two instance mongodb use spring boot and spring data
[英]How to fetch data from mongoDB based on two dates in spring boot?
我在 spring 引導中使用聚合。 但得到響應為 null
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
class 具有andOperator
。 你需要把你的條件傳遞給那個。
query.addCriteria(
new Criteria().andOperator(
Criteria.where("createdAt").lt(fromDate),
Criteria.where("createdAt").gt(toDate)
)
);
另一種選擇是查詢注釋。
@Query("{'createdAt': { $gte: ?0, $lte: ?1 } }")
這里, ?0
代表 function 的第一個參數, $1
代表 function 的第二個參數。
嘗試了解您可以通過函數名稱創建的內置方法
@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 引導。
我的項目舊版本是
<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>
代碼的rest同上。
所以它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.