'How to find record with date query in MongoRepository
I have a collection called Example:
public class Example extends PersistObject {
private LocalDate startDate;
private LocalDate endDate;
private String code;
}
I want to find a document with a particular code that has startDate and endDate where the current date falls in between.
How can I get this with MongoRepository supported keywords?
Solution 1:[1]
Not sure about creating a query for MongoDB. For SQL syntax you could get the current date and pass it to a query like:
SELECT * FROM Example WHERE code=myCode
AND nowDate BETWEEN startDate AND endDate;
If you use something like Spring Data you could create a specified method for ExampleRepository:
@Query("from Example where code = :code " +
"and :date between startDate and endDate")
Example getAllExampleByCode(@Param("code") String code, @Param("date") LocalDate date);
However, you need to know that code param is unique and you will get only 1 result.
Otherwise, you will get an entity, not a unique exception. Or make method return List<Example>.
And when you will call it from the service layer you could pass date param:
exampleRepo.getAllExampleByCode("myCode", LocalDate.now());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
