Alesto
Alesto

Reputation: 689

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

Upvotes: 3

Views: 11940

Answers (1)

s7vr
s7vr

Reputation: 75964

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

Upvotes: 8

Related Questions