Dmitry Igumnov
Dmitry Igumnov

Reputation: 165

Spring java MongoDB @Query annotation for order top or first records

I use @Query annotation and crudRepository to fetch data from MongoDB. Example:

@Query("{$query: id: ?0}, $orderby: {dateTime: -1}}")
public List<A> findId(
    Integer id, Pageable pageable
);

What do I need to add to my @Query notation if i want to fetch only first N records of collection, or only top N records of collection? I would like to use dynamic query and dynamic set limit and order (first or top records).

Upvotes: 4

Views: 12492

Answers (2)

masy
masy

Reputation: 1

Use the variable sort of the @Query:

@Query(value = "{}", sort = "{ _id : -1 }")

As an example for "order by id desc".

Upvotes: 0

Zava
Zava

Reputation: 400

you can append your @Query with $limit : 10, or rename your method like : find First10ByDateDesc()

Upvotes: 4

Related Questions