首页 > 其他分享 >mongo page query based on conditions

mongo page query based on conditions

时间:2024-03-19 09:46:17浏览次数:20  
标签:Sort based pageable studentVO Student new query conditions

一、MongoTemplate 中 Aggregation 应用

  • 使用Aggregation聚合查询
  • 支持返回固定字段
  • 支持分组计算(count)总数、(sum)求和、(avg)平均值、(max)最大值、(min)最小值等
public Page<Student> getListWithAggregation(StudentVO studentVO) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); 
    Pageable pageable = PageRequest.of(studentVO.getPageNum(), studentVO.getPageSize(), sort);
    Integer pageNum = studentVO.getPageNum();
    Integer pageSize = studentVO.getPageSize();
    List<AggregationOperation> operations = new ArrayList<>();   
    if (!StringUtils.isEmpty(studentVO.getName())) {       
           Pattern pattern = Pattern.compile("^.*" + studentVO.getName() + ".*$", Pattern.CASE_INSENSITIVE);       
           Criteria criteria = Criteria.where("name").regex(pattern);
operations.add(Aggregation.match(criteria)); } if (null != studentVO.getSex()) {
operations.add(Aggregation.match(Criteria.where("sex").is(studentVO.getSex())));
}
          //获取满足添加的总页数 
      long totalCount = 0; if (null != operations && operations.size() > 0) {
        Aggregation aggregationCount = Aggregation.newAggregation(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;
}

 

二、MongoTemplate 结合 BasicQuery 的集合应用

public Page<Student> getListWithBasicQuery(StudentVO studentVO) {
// 排序 Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); Pageable pageable = PageRequest.of(studentVO.getPageNum(), studentVO.getPageSize(), sort); QueryBuilder queryBuilder = new QueryBuilder(); if (!StringUtils.isEmpty(studentVO.getName())) {
// 模糊查询 Pattern pattern = Pattern.compile("^.*" + studentVO.getName() + ".*$", Pattern.CASE_INSENSITIVE); queryBuilder.and("name").regex(pattern);
} if (studentVO.getSex() != null) {
queryBuilder.and("sex").is(studentVO.getSex()); } if (studentVO.getCreateTime() != null) {
queryBuilder.and("createTime").lessThanEquals(studentVO.getCreateTime()); } Query query = new BasicQuery(queryBuilder.get().toString());
//计算总数
long total = mongoTemplate.count(query, Student.class);
//查询结果集条件
BasicDBObject fieldsObject = new BasicDBObject();
    fieldsObject.append("id", 1).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结合Example和Criteria 的集合查询应用

public Page<Student> getListWithExampleAndCriteria(StudentVO studentVO) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
    Pageable pageable = PageRequest.of(studentVO.getPageNum(), studentVO.getPageSize(), sort);
    Student student = new Student();
    BeanUtils.copyProperties(studentVO, 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 (studentVO.getCreateTime() != null){
query.addCriteria(Criteria.where("createTime").lte(studentVO.getCreateTime()));
} //计算总数 long total = mongoTemplate.count(query, Student.class); //查询结果
List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class); Page<Student> stuPageList = new PageImpl(studentList, pageable, total);
return stuPageList; }

四、MongoTemplate结合Query 的集合查询应用

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

五、MongoTemplate结合 ExampleMatcher 的集合查询应用

  • 使用ExampleMatcher匹配器-----只支持字符串的模糊查询,其他类型是完全匹配
  • Example封装实体类和匹配器
  • 使用ExampleExecutor 接口中的findAll方法
public Page<Student> getListWithExample(StudentVO studentVO) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
    Pageable pageable = PageRequest.of(studentVO.getPageNum(), studentVO.getPageSize(), sort);
    Student student = new Student();
    BeanUtils.copyProperties(studentVO, 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;
}

 

标签:Sort,based,pageable,studentVO,Student,new,query,conditions
From: https://www.cnblogs.com/northeastTycoon/p/18081981

相关文章

  • jQuery+CSS3自动轮播焦点图特效源码
    jQuery+CSS3自动轮播焦点图特效源码,源码由HTML+CSS+JS组成,双击html文件可以本地运行效果,也可以上传到服务器里面下载地址jQuery+CSS3自动轮播焦点图特效源码......
  • 在Linux中,在不同的Linux发行版中(如RPM-based和DEB-based)如何安装、升级、删除软件包?
    在Linux中,不同的发行版采用了不同的包管理器来处理软件安装、升级和删除操作。以下是基于RPM(RedHatPackageManager)系统(如RedHatEnterpriseLinux,CentOS,Fedora等)和基于DEB(Debianpackage)系统的(如Debian,Ubuntu,LinuxMint等)的操作说明:1.RPM-based系统(使用yum或dnf......
  • 基于Rust的Tile-Based游戏开发杂记(02)ggez绘图实操
    尽管ggez提供了很多相关特性的demo供运行查看,但笔者第一次使用的时候还是有很多疑惑不解。经过仔细阅读demo代码并结合自己的实践,逐步了解了ggez在不同场景下的绘图方式,在此篇文章进行一定的总结,希望能够帮助到使用ggez的读者。供运行查看,但笔者第一次使用的时候还是有很多疑惑不......
  • FireDAC中FDQuery1中SQL语句中的参数使用
    假设数据库已正常连接双击FDQuery1,SQL语句中以冒号开头就是参数,后面就是参数名 然后第二Parameters页,左边列表就有就该参数名,然后给参数的DataType,Value值,再点Execute,就可看到查询结果。 其后将上面的界面,变成代码实现即可procedureTForm13.Button1Click(Sende......
  • jQuery基础
    jQuery是JavaScript的第三方的模块组件(类库),可以利用jQuery来实现bootstrap的动态效果(目前bootstrapV5可以不依赖jQuery就能实现效果)首先需要下载jQuery,存放到pycharm的web中的static目录下引用方式和JavaScript一致,在body的尾部写入<scriptsrc=".../.../jQuery.min.j......
  • P2824 [HEOI2016/TJOI2016] 排序 与 ABC297_g Range Sort Query 题解
    洛谷题目链接:排序abc题目链接:Atcoder或者洛谷两道差不多的题拿出来说说。本题有双\(\log\)做法,也有单\(\log\)做法,都讲讲。双\(\log\)做法对于第一个题而言,询问最终\(pos\)位置上的数为多少,那么这个问题是否具有单调性?这个是很有意思的点,我们考虑只关注某个数\(x\)......
  • 【译】Based:简单线性注意力语言模型平衡召回-吞吐量权衡
    原文:hazyresearch.stanford.edu/blog/2024-03-03-based全体团队:Simran,Sabri,Michael*,Aman,Silas,Dylan,James,Atri,ChrisArxiv:arxiv.org/abs/2402.18668代码:github.com/HazyResearch/based在ICLR论文(以及博客文章)中,我们在去年年底分享了一个发现,许多高效的架构(例如Mamba,RWKV,Hyena......
  • vue中router页面之间参数传递,params失效,建议使用query
    vue中router页面之间参数传递,params失效,建议使用query简介:本文讲解vue中router页面之间参数传递,params失效,建议使用query。在vue中有一个router功能,他可以用来页面之间的参数传递,他有两种方式一种是params方式,一种是query方式,但是params方式特别容易导致参数的丢失问......
  • 都2024年了还在写JQuery?一篇文章带你快速入门Vue.js
    Vue快速入门笔记本文主要介绍vue.js的核心知识点,看完本篇文章只能算是简单入门了解Vue,后续还需要读者在项目中不断练习研究。一、前端核心分析1.1、概述Soc原则:关注点分离原则Vue的核心库只关注视图层,方便与第三方库或既有项目整合。HTML+CSS+JS:视图:给用户......
  • openGauss备库wal-replay与query冲突
    openGauss备库walreplay与query冲突概述openGauss的物理流复制逻辑继承了PostgreSQL,当一条数据从主库做变更到可以在备库查询到最新的值,在PostgreSQL备库分为三个阶段,分别是写入备库操作系统(remote_write),将缓存中的数据刷入到磁盘(on==flush),从磁盘将数据库回放(remot......