[英]How can I sort and do a search in mongodb spring boot
I cannot sort my search results using Mongodb, I added a method query that uses findAllByorderByDateDesc()我无法使用 Mongodb 对搜索结果进行排序,我添加了一个使用 findAllByorderByDateDesc() 的方法查询
I tried using "findAllByOrderByDateDesc() and it works if I'm not doing a search query but once I add the @Query annotation it stops sorting by dates.我尝试使用“findAllByOrderByDateDesc(),如果我没有进行搜索查询,它会起作用,但是一旦我添加了@Query 注释,它就会停止按日期排序。
Repository资料库
@Repository
public interface WarrantiesRepository extends MongoRepository<WarrantyModel, String> {
public Page<WarrantyModel> findAllByOrderByDateDesc(PageRequest pageRequest);
@Query("{$text: {$search: ?0}}")
public Page<WarrantyModel> findAllByOrderByDateDesc(String search, PageRequest pageRequest);
public WarrantyModel getWarrantyById(String id);
public WarrantyModel getWarrantyByCar(String car);
public WarrantyModel getWarrantyByPart(String part);
public WarrantyModel getWarrantyBypartNumber(String partNumber);
}
Controller控制器
@PostMapping("/warranties/search")
public ModelAndView getLiveWarranties(@RequestBody String search, Model model) {
input = search.substring(1, search.length()-1);
if(search.length() == 2) {
warranties = warrantiesRepository.findAllByOrderByDateDesc(PageRequest.of(currentPage, pageSize));
} else {
warranties = warrantiesRepository.findAllByOrderByDateDesc(search, PageRequest.of(currentPage, pageSize));
}
ModelAndView mv = new ModelAndView("warranties::search");
mv.addObject("warranties", warranties);
return mv;
}
Model模型
@Component
@Document("Warranty")
public class WarrantyModel {
@Id
public String id;
@TextIndexed
public String car;
@TextIndexed
public String part;
public String store;
@TextIndexed
public String partNumber;
public String warranty;
public LocalDate date;
Constructors/getter/setters
This is the expected behavior.这是预期的行为。 By default all the methods of a '...Repository' are 'derived query methods' and Spring tries to map the implementation based on the method name (It will generate the queries for you).
默认情况下,“...Repository”的所有方法都是“派生查询方法”,Spring 会尝试根据方法名称映射实现(它将为您生成查询)。
Once you annotate a method with @Query
annotation, Spring expects you to specify your own query and will not do any derivation on its own irrespective of the name of the method.一旦你用
@Query
注释注释了一个方法,Spring 希望你指定你自己的查询,并且无论方法的名称如何,它都不会自己做任何派生。
Check this article for more detailed explanation - Spring Data MongoDB - Guide to the @Query Annotation查看这篇文章以获得更详细的解释 - Spring Data MongoDB - Guide to the @Query Annotation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.