Search code examples
mongodbspring-bootmongorepository

Can I use MongoRepository to sort in the order of the score?


I'm going to sort the search results in the database in the order of the score.

However, I could not find a way to sort using mongoRepository, so I asked a question.

Is there a way to sort by socre using MongoRepository?

This is my Entity

    @Data
    @Document(collection = "cad")
    public class Cad {
        @Id
        private String id;
        private String author;
        private String mainCategory;
        private String subCategory;
        private String title;
        private String index;
        private String s3Url;
        private String createdAt;
    
    
        public Cad(String author, String mainCategory, String subCategory, String title, String index, String s3Url, String createdAt) {
            this.author = author;
            this.mainCategory = mainCategory;
            this.subCategory = subCategory;
            this.title = title;
            this.index = index;
            this.s3Url = s3Url;
            this.createdAt = createdAt;
        }
    }

And This is my Repository

    public interface CadRepository extends MongoRepository<Cad, String> {
        List<Cad> findAllByTitleOrIndexOrMainCategoryOrSubCategoryContains(String text1, String text2, String text3, String text4);
    }

And This is my Service

@RequiredArgsConstructor
@Service
@Component
public class CadService {
    private final CadRepository cadRepository;

    public List<Cad> searchCadFile(String searchText) {
        try {
            List<Cad> list = cadRepository.findAllByTitleOrIndexOrMainCategoryOrSubCategoryContains(searchText, searchText, searchText, searchText);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

I tried @Aggregate Annotation, but I didn't get the result I wanted.

Any hint would be appreciated. Thank you :)


Solution

  • You can add a org.springframework.data.domain.Sort parameter to your repository method:

    List<Cad> findAllByTitleOrIndexOrMainCategoryOrSubCategoryContains(String text1, String text2, String text3, String text4, Sort sort);
    
    

    And when calling your repository method you can add the property / properties you want to sort on:

    List<Cad> list = cadRepository.findAllByTitleOrIndexOrMainCategoryOrSubCategoryContains(searchText, searchText, searchText, searchText, Sort.by("index"));
    
    

    Or you can add the property to the method name:

    List<Cad> findAllByTitleOrIndexOrMainCategoryOrSubCategoryContainsOrderByIndexAsc(String text1, String text2, String text3, String text4);
    
    

    Things are more explained in detail here: https://www.baeldung.com/spring-data-sorting