Home > Software engineering >  sorted in desending order using mongoRepository
sorted in desending order using mongoRepository

Time:04-05

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

CodePudding user response:

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.

CodePudding user response:

for @Query annotation: 1 = ASC, -1 = DESC

@Query(sort="{'name':-1}")
List<file> findByName(String name);
  • Related