Find entity with latest date using Spring Data with MongoDB

Alesto picture Alesto · Jun 4, 2017 · Viewed 7.4k times · Source

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);
}

Answer

s7vr picture s7vr · Jun 5, 2017

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();