MongoDB动态条件之分页查询

一、使用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;}
 

原文地址:https://www.cnblogs.com/wslook/p/9275861.html

时间: 2024-08-06 05:48:43

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

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

HBase是Apache Hadoop生态系统中的重要一员,它的海量数据存储能力,超高的数据读写性能,以及优秀的可扩展性使之成为最受欢迎的NoSQL数据库之一.它超强的插入和读取性能与它的数据组织方式有着密切的关系,在逻辑上,HBase的表数据按RowKey进行字典排序, RowKey实际上是数据表的一级索引(Primary Index),由于HBase本身没有二级索引(Secondary Index)机制,基于索引检索数据只能单纯地依靠RowKey.也只有使用RowKey查询数据才能得到非常高

动态sql实现分页查询

1.创建实体类对象需要查询的条件com.rl.ecps.model.QueryCondition private Long brandId; private Short auditStatus; private Short showStatus; private String itemName; private Integer pageNo; private Integer startNum; private Integer endNum; 2.查询语句 查询条数: <select id="

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

查询窗口中可以设置很多查询条件 表单中输入的内容转为datagrid的load方法所需的查询条件向原请求地址再次提出新的查询,将结果显示在datagrid中 转换方法看代码注释 <td colspan="2"><a id="searchBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'"&g

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

使用ExtJs的同志们一定知道GridPanel哈~神器一般,非常方便的显示表格类型的数据,例如神马用户列表.产品列表.销售单列表.XXXX列表等.从数据库中查询所需的数据,以列表的形式显示出来,我们理应想到对这种数据实现搜索. 搜索最简单的方法就是reload那个与GridPanel关联的store,将搜索结果存进去,但是最初实现的搜索都把原来GridPanel的那个分页功能给破坏掉了. 原因:        给store重新载入数据后,PagingToolbar不起作用了,因为ExtJs默认

条件和分页查询

Mapper: <select id="queryBlackByMac" resultMap="BlackByMac"> SELECT packet_black_mac_id, mac, creator, create_time FROM flnet_system_ota.packet_black_mac <where> <if test=" mac!=null and mac!='' "> mac LIKE

有条件的,分页查询

<body> <br /> <!--查询表格--> <?php $name=""; $tj=""; //分页条件 if(!empty($_GET["name"])) //多条件查询 { $name = $_GET["name"]; $tj = " where table_name like '%{$name}%'"; } ?> <form> 关键字

有条件分页查询功能实现

1. 制作查询按钮,点击按钮 显示快递员查询表单(窗口)2. 将查询窗口条件,绑定到数据表格上,让数据表格在发送请求时,自动携带条件查询 jquery easyui datagrid 数据表格 api先将页面 form 表单中数据,转换 {key:value, key:value} 格式查看 jquery 基于自定义方法,完成将 form 参数转换为 json 绑定 datagrid 上查询条件和分页查询参数 一起发送给服务器端3. 修改 CourierAction 的 pageQuery 方法

大数据oracle分页查询

ROWNUM 可能都知道ROWNUM只适用于小于或小于等于,如果进行等于判断,那么只能等于1,不能进行大于的比较. ROWNUM是oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是2,依此类推. ROWNUM总是从1开始,不管当前的记录是否满足查询结果,ROWNUM返回的值都是1,如果这条记录的值最终满足所有的条件,那么ROWNUM会递加,下一条记录的ROWNUM会返回2,否则下一条记录的ROWNUM仍然返回1. 理解了这一点,就清楚为什么一般的ROWNUM大于某个

Oracle ROWNUM用法和分页查询总结

********************************************************************************************************** [转载] Oracle的分页查询语句基本上可以按照本文给出的格式来进行套用. Oracle分页查询格式(一):http://yangtingkun.itpub.net/post/468/100278 Oracle分页查询格式(二):http://yangtingkun.itpub.ne