MongoDB分页和条件查询

朴灿烈づ我的快乐病毒、 2022-12-08 15:48 284阅读 0赞

MongoDB 分页和条件查询

mongoDB 很多需求页面需要分页也需要条件查询,Spring Data MongoDB中就帮助我们实现了这一功能,所以只要记住怎么用就可以很轻松的写出。废话不多说。下面写出我现在正在写的代码,共大家参考参考,下面还有解释。

  1. @Autowired
  2. CmsPageRepository cmsPageRepository;
  3. /**
  4. * 查询每页的CmsPage
  5. *
  6. * @param page 当前页数
  7. * @param size 每页显示的条数
  8. * @param queryPageRequest 查询条件
  9. * @return 返回每页的CmsPage
  10. */
  11. public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest) {
  12. page = page <= 0 ? 1 : page;
  13. size = size > 10 ? 10 : size;
  14. // 条件查询
  15. // 页面名称使用模糊查询 站点id使用精确查询
  16. ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());
  17. // 条件
  18. CmsPage cmsPage = new CmsPage();
  19. if (queryPageRequest != null){
  20. if ( StringUtils.isNotEmpty(queryPageRequest.getPageAliase())) {
  21. cmsPage.setPageAliase(queryPageRequest.getPageAliase());
  22. }
  23. if (StringUtils.isNotEmpty(queryPageRequest.getSiteId())) {
  24. cmsPage.setSiteId(queryPageRequest.getSiteId());
  25. }
  26. }
  27. Example<CmsPage> example = Example.of(cmsPage,exampleMatcher);
  28. Page<CmsPage> cmsPagePages = cmsPageRepository.findAll(example,new PageRequest(page, size));
  29. QueryResult<CmsPage> cmsPageQueryResult = new QueryResult<>();
  30. if (cmsPagePages != null){
  31. cmsPageQueryResult.setList(cmsPagePages.getContent()); //每页封装page
  32. cmsPageQueryResult.setTotal(cmsPagePages.getTotalElements()); // 总条数
  33. }
  34. return new QueryResponseResult(CommonCode.SUCCESS,cmsPageQueryResult);
  35. }
  1. 首先前面两行就不用我说了,就是防止前端传过来的数据不符合规定,所以就先做了下判断。
  2. .ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());
    这一段代码就是把一个条件进行模糊查询,其中“pageAliase”就是模糊查询的条件。所以你们想用自己的条件的话,只需要把这个地方修改下就可以了。
  3. MongoDB有一张表对应的是CmsPage类。
  4. 根据前端传来的对象判断是哪个条件有值,有值的条件就set到CmsPage 这个对象中,注意;(如果要是想精确查询的话,不需要写第二步骤的代码,直接就set进去值就可以了)
  5. Example<CmsPage> example = Example.of(cmsPage,exampleMatcher); 把这个条件和查询方式放到这个里面就可以了。
  6. 然后使用Spring Data MongoDB 里面的一个findAll();方法填写相对应的参数就可以了。这样就可以实现分页和条件查询。

还有和多查询方式我在下面也列举出来,当需要用到的可以看看这下面。


























endWith 以什么结尾
startWith 以什么开始查询
regex 正则表达式查询
ignoreCase 忽略大小写查询
contains 模糊查询

发表评论

表情:
评论列表 (有 0 条评论,284人围观)

还没有评论,来说两句吧...

相关阅读