spring-bootmongorepository

sorted in desending order using mongoRepository


I am a beginner on spring boot and mongodb I want to use @query to display the files in descending order can you give me an idea?

public class file{
    private String id;
    private String name;
    private LocalDateTime datecreated;
    
    // constructor, getters, setters  
}

public interface FileRepository extends MongoRepository<file, String> {
    
  // @Query("{}")
   List<file> findByname(String name);
}

Solution

  • If you're writing custom queries in your repository layer, you can sort on invocation. You can follow an approach as below.

    Repository:

    @Query("{...}")
    List<file> findByname(String name, Sort sort);
    

    Sort on invocation:

    Sort sort = new Sort(Sort.Direction.DESC, "sorting field");
    List<file> data = repository.findByname(name, sort);
    

    There can be multiple ways to do this. This is just one of them.

    Hope this helps for you.