一、使用QueryByExampleExecutor

1. 继承MongoRepository

public interface StudentRepository extends MongoRepository<Student, String> {

}

2. 代码实现

  • 使用ExampleMatcher匹配器-----只支持字符串的模糊查询,其他类型是完全匹配
  • Example封装实体类和匹配器
  • 使用QueryByExampleExecutor接口中的findAll方法
public Page<Student> getListWithExample(StudentReqVO studentReqVO) {
Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Student student = new Student();
BeanUtils.copyProperties(studentReqVO, student); //创建匹配器,即如何使用查询条件
ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
.withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写
.withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //采用“包含匹配”的方式查询
.withIgnorePaths("pageNum", "pageSize"); //忽略属性,不参与查询 //创建实例
Example<Student> example = Example.of(student, matcher);
Page<Student> students = studentRepository.findAll(example, pageable); return students;
}

缺点:

  • 不支持过滤条件分组。即不支持过滤条件用 or(或) 来连接,所有的过滤条件,都是简单一层的用 and(并且) 连接
  • 不支持两个值的范围查询,如时间范围的查询

二、MongoTemplate结合Query

实现一:使用Criteria封装查询条件

public Page<Student> getListWithCriteria(StudentReqVO studentReqVO) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Query query = new Query(); //动态拼接查询条件
if (!StringUtils.isEmpty(studentReqVO.getName())){
Pattern pattern = Pattern.compile("^.*" + studentReqVO.getName() + ".*$", Pattern.CASE_INSENSITIVE);
query.addCriteria(Criteria.where("name").regex(pattern));
} if (studentReqVO.getSex() != null){
query.addCriteria(Criteria.where("sex").is(studentReqVO.getSex()));
}
if (studentReqVO.getCreateTime() != null){
query.addCriteria(Criteria.where("createTime").lte(studentReqVO.getCreateTime()));
} //计算总数
long total = mongoTemplate.count(query, Student.class); //查询结果集
List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class);
Page<Student> studentPage = new PageImpl(studentList, pageable, total);
return studentPage;
}

实现二:使用Example和Criteria封装查询条件

public Page<Student> getListWithExampleAndCriteria(StudentReqVO studentReqVO) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Student student = new Student();
BeanUtils.copyProperties(studentReqVO, student); //创建匹配器,即如何使用查询条件
ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
.withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写
.withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //标题采用“包含匹配”的方式查询
.withIgnorePaths("pageNum", "pageSize"); //忽略属性,不参与查询 //创建实例
Example<Student> example = Example.of(student, matcher);
Query query = new Query(Criteria.byExample(example));
if (studentReqVO.getCreateTime() != null){
query.addCriteria(Criteria.where("createTime").lte(studentReqVO.getCreateTime()));
} //计算总数
long total = mongoTemplate.count(query, Student.class); //查询结果集
List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class);
Page<Student> studentPage = new PageImpl(studentList, pageable, total);
return studentPage;
}

缺点:

  • 不支持返回固定字段

三、MongoTemplate结合BasicQuery

  • BasicQuery是Query的子类
  • 支持返回固定字段
public Page<Student> getListWithBasicQuery(StudentReqVO studentReqVO) {
Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); QueryBuilder queryBuilder = new QueryBuilder(); //动态拼接查询条件
if (!StringUtils.isEmpty(studentReqVO.getName())) {
Pattern pattern = Pattern.compile("^.*" + studentReqVO.getName() + ".*$", Pattern.CASE_INSENSITIVE);
queryBuilder.and("name").regex(pattern);
} if (studentReqVO.getSex() != null) {
queryBuilder.and("sex").is(studentReqVO.getSex());
}
if (studentReqVO.getCreateTime() != null) {
queryBuilder.and("createTime").lessThanEquals(studentReqVO.getCreateTime());
} Query query = new BasicQuery(queryBuilder.get().toString());
//计算总数
long total = mongoTemplate.count(query, Student.class); //查询结果集条件
BasicDBObject fieldsObject = new BasicDBObject();
//id默认有值,可不指定
fieldsObject.append("id", 1) //1查询,返回数据中有值;0不查询,无值
.append("name", 1);
query = new BasicQuery(queryBuilder.get().toString(), fieldsObject.toJson()); //查询结果集
List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class);
Page<Student> studentPage = new PageImpl(studentList, pageable, total);
return studentPage;

四、MongoTemplate结合Aggregation

  • 使用Aggregation聚合查询
  • 支持返回固定字段
  • 支持分组计算总数、求和、平均值、最大值、最小值等等
public Page<Student> getListWithAggregation(StudentReqVO studentReqVO) {
Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Integer pageNum = studentReqVO.getPageNum();
Integer pageSize = studentReqVO.getPageSize(); List<AggregationOperation> operations = new ArrayList<>();
if (!StringUtils.isEmpty(studentReqVO.getName())) {
Pattern pattern = Pattern.compile("^.*" + studentReqVO.getName() + ".*$", Pattern.CASE_INSENSITIVE);
Criteria criteria = Criteria.where("name").regex(pattern);
operations.add(Aggregation.match(criteria));
}
if (null != studentReqVO.getSex()) {
operations.add(Aggregation.match(Criteria.where("sex").is(studentReqVO.getSex())));
}
long totalCount = 0;
//获取满足添加的总页数
if (null != operations && operations.size() > 0) {
Aggregation aggregationCount = Aggregation.newAggregation(operations); //operations为空,会报错
AggregationResults<Student> resultsCount = mongoTemplate.aggregate(aggregationCount, "student", Student.class);
totalCount = resultsCount.getMappedResults().size();
} else {
List<Student> list = mongoTemplate.findAll(Student.class);
totalCount = list.size();
} operations.add(Aggregation.skip((long) pageNum * pageSize));
operations.add(Aggregation.limit(pageSize));
operations.add(Aggregation.sort(Sort.Direction.DESC, "createTime"));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<Student> results = mongoTemplate.aggregate(aggregation, "student", Student.class); //查询结果集
Page<Student> studentPage = new PageImpl(results.getMappedResults(), pageable, totalCount);
return studentPage;
}
 

MongoDB动态条件之分页查询的更多相关文章

  1. mybatis动态条件组合分页查询

    一.动态条件处理 需要使用mybatis的动态sql 1 <select id="selectItemByCondition" parameterType="com ...

  2. mysq带条件的分页查询数据结果错误

    记一次mysql分页条件查询的结果出错: 以一张用户表为例,首先我们看表中的所有数据,注意红色框住的部分: 我们使用不带条件的分页查询来查询,数据显示是OK的: SELECT id,login_nam ...

  3. Spring Data JPA 复杂/多条件组合分页查询

    推荐视频: http://www.icoolxue.com/album/show/358 public Map<String, Object> getWeeklyBySearch(fina ...

  4. laravel 带条件的分页查询

    laravel 带条件的分页查询, 原文:http://blog.csdn.net/u011020900/article/details/52369094 bug:断点查询,点击分页,查询条件消失. ...

  5. spring mongodb分页,动态条件、字段查询

    使用MongRepository public interface VideoRepository extends MongoRepository<Video, String> { Vid ...

  6. HBase多条件及分页查询的一些方法

    HBase是Apache Hadoop生态系统中的重要一员,它的海量数据存储能力,超高的数据读写性能,以及优秀的可扩展性使之成为最受欢迎的NoSQL数据库之一.它超强的插入和读取性能与它的数据组织方式 ...

  7. 序列化表单为json对象,datagrid带额外参提交一次查询 后台用Spring data JPA 实现带条件的分页查询 多表关联查询

    查询窗口中可以设置很多查询条件 表单中输入的内容转为datagrid的load方法所需的查询条件向原请求地址再次提出新的查询,将结果显示在datagrid中 转换方法看代码注释 <td cols ...

  8. ExtJs3带条件的分页查询的实现

    使用ExtJs的同志们一定知道GridPanel哈~神器一般,非常方便的显示表格类型的数据,例如神马用户列表.产品列表.销售单列表.XXXX列表等.从数据库中查询所需的数据,以列表的形式显示出来,我们 ...

  9. springboot+mongodb 按日期分组分页查询

    List<Integer> types = new ArrayList<>(); types.add("条件1"); types.add("条件2 ...

随机推荐

  1. LeetCode 773. Sliding Puzzle

    原题链接在这里:https://leetcode.com/problems/sliding-puzzle/description/ 题目: On a 2x3 board, there are 5 ti ...

  2. Ubuntu sudo: add-apt-repository: command not found

    安装缺少的指令即可 $ sudo apt-get install software-properties-common python-software-properties

  3. RK3288 增加双屏异显 eDP+LVDS

    CPU:RK3288 系统:Android 5.1 下面是官方文档中的信息. 1.rk3288 支持的显示接口可以任意组合. 2.双屏异显时,一个显示接口当主屏,另一个当副屏:主副屏由板级 dts 文 ...

  4. Linux 制作补丁 打补丁 撤销补丁

    1.制作补丁 diff - 逐行比较文件 格式 diff   参数   旧文件/旧文件夹   新文件/新文件夹 -N   将不存在的文件看作是空的 -a   将所有文件都视为文本文件 -u   以合并 ...

  5. 免费数据集下载网站【dataset】

    https://github.com/awesomedata/awesome-public-datasets

  6. erlang里面中文相关处理

    在控制台输出的话 Name = "测试数据", io:format("~ts~n",[Name]). 如果是和客户端通信,假如都是utf8编码 服务器获取的时候 ...

  7. golang里面检测对象是否实现了接口的方法

    写法有点怪异,记一下吧 _, implemented := this.delegate.(IGenTcpServerDelegate) if implemented { this.delegate.G ...

  8. temple-html5

    ylbtech-HTML5:  1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   7.返回顶部   8.返回顶部   9.返回顶部   1 ...

  9. video2gift环境安装(Theano等)

    pip install Theano http://deeplearning.net/software/theano/install_centos6.html pip install moviepy ...

  10. java后台读取配置文件中key与value -----demo

    public class ResourcesUtils { /* * @description:根据属性获取文件名 * * @param:propertyName文件的属性名 * * @return: ...