0

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?

2
  • For any enterprise quality solutions, use MongoTemplate instead of MongoRepository. MongoTemplate provides much more control. This is especially important if the application grows large and needs to scale via sharding. Commented Jan 25, 2022 at 16:37
  • @dineshalwis is your question resolved? Commented Jun 29, 2022 at 7:22

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

0

I also had this issue having the LocalDate datatype. What worked for me was, based on your case:

List<Example> findByCodeAndEndDateIsGreaterThanEqualAndStartDateIsLessThanEqual(final String code, final Date d1, final Date d2)

where d1 and d2 would have today's date:

LocalDate today = LocalDate.now();
Date date = Date.from(today.atStartOfDay(ZoneOffset.UTC).toInstant());

It's important to notice the time zone ZoneOffset.UTC should match your MongoDB configuration so you don't miss any results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.