Search code examples
mongodbspring-dataspring-data-mongodblocaldate

Find entity with latest date using Spring Data with MongoDB


Given next object structure:

class Foo {
  @Id
  String id;
  LocalDate date;
  ...
}

We store these objects in MongoDB. Is there any possibility to get entity with the latest date via MongoRepository like in the next example?

interface FooRepository extends MongoRepository<Foo, String> {
    @Query(???)
    Foo getByLatestDate(LocalDate date);
}

Solution

  • You can try below query.

    Using @Query annotation

    @Query("{ 'date' : ?0 }")
    Foo getByLatestDate(LocalDate date);
    

    Or

    Using repository supported keywords

    Foo findByDate(LocalDate date);
    

    Update: Use below query to get latest date.

    Foo findFirstByOrderByDateDesc();
    
    Foo findTopByOrderByDateDesc();