聚合方法实现了什么功能

条件查询,分组,统计,关联查询,排序,分页,返回指定字段

聚合方法:

AggregationResults<DocumentEntity> results = mongoTemplate.aggregate(aggregation, TableNameUtils.getDocTableName(request.getCompanyId()), DocumentEntity.class);源码:
@Override
public <O> AggregationResults<O> aggregate(Aggregation aggregation, String collectionName, Class<O> outputType) {return aggregate(aggregation, collectionName, outputType, null);
}
参数1:Aggregation,看下这个对象的方法,可以看到入参有两种,集合/数组public static Aggregation newAggregation(List<? extends AggregationOperation> operations) {return newAggregation(operations.toArray(new AggregationOperation[operations.size()]));
}public static Aggregation newAggregation(AggregationOperation... operations) {return new Aggregation(operations);
}

1,关联查询

需求:有三张表,档案表,发票表,文件表,发票表和文件表通过字段文档流水号(documentSerialNum),与档案表字段(serialNum)流水号关联,现在要根据serialNum查询文档表及其下面的发票和发票信息(1:n)。

代码:

private List<DocumentEntity> getDocumentEntities(BaseRequestModel request, List<String> serialNumS) {// 文件和发票表通过外键查询LookupOperation lookupOperation = LookupOperation.newLookup().from("table_file").localField("serialNum").foreignField("documentSerialNum").as("docs");LookupOperation lookupOperationinv = LookupOperation.newLookup().from("table_inv").localField("serialNum").foreignField("documentSerialNum").as("docs2");// 拼装具体查询信息Criteria docCri = Criteria.where("docs").not().size(0);docCri.and("serialNum").in(serialNumS);docCri.and("isDel").is(IsDelEnum.NO.getValue());docCri.and("docs.isDel").is(IsDelEnum.NO.getValue());docCri.and("docs2.isDel").is(IsDelEnum.NO.getValue());AggregationOperation match = Aggregation.match(docCri);// 把条件封装成ListList<AggregationOperation> operations = new ArrayList<>();operations.add(lookupOperation);operations.add(lookupOperationinv);operations.add(match);// 构建 Aggregation Aggregation aggregation = Aggregation.newAggregation(operations);// 执行查询AggregationResults<DocumentEntity> results = mongoTemplate.aggregate(aggregation, "table_doc", DocumentEntity.class);// 或者入参为数组Aggregation aggregation = Aggregation.newAggregation(lookupOperation,lookupOperationinv,Aggregation.match(docCri));return results.getMappedResults();
}

特别注意的一点:主字段和外键对应哪个表,指的是mongoTemplate.aggregate(),方法中的表

localField:table_doc主字段 serialNum

foreignField:table_inv table_file 外键 documentSerialNum

LookupOperation lookupOperation = LookupOperation.newLookup(). from("table_file"). localField("serialNum"). foreignField("documentSerialNum"). as("docs");

2,返回指定字段,分组,统计,排序,分页

详细见原文:

https://www.jianshu.com/p/78b96ca40927

https://www.cnblogs.com/wslook/p/9831842.html

需求:在订单表中,根据buyerNick分组,统计每个buyerNick的电话、地址、支付总金额以及总商品数,返回结果是CustomerDetail。

/** project:列出所有本次查询的字段,包括查询条件的字段和需要搜索的字段;* match:搜索条件criteria* unwind:某一个字段是集合,将该字段分解成数组* group:分组的字段,以及聚合相关查询*      sum:求和(同sql查询)*      count:数量(同sql查询)*      as:别名(同sql查询)*      addToSet:将符合的字段值添加到一个集合或数组中* sort:排序* skip&limit:分页查询*/
public List<CustomerDetail> customerDetailList(Integer pageNum,String userId,String buyerNick,String itemId,List<String> phones) throws Exception{Criteria criteria = Criteria.where("userId").is(userId);Integer pageSize = 10;Integer startRows = (pageNum - 1) * pageSize;if(buyerNick != null && !"".equals(buyerNick)){criteria.and("buyerNick").is(buyerNick);}if(phones != null && phones.size() > 0){criteria.and("mobile").in(phoneList);}if(itemId != null && !"".equals(itemId)){criteria.and("orders.numIid").is(itemId);}Aggregation customerAgg = Aggregation.newAggregation(Aggregation.project("buyerNick","payment","num","tid","userId","address","mobile","orders"),Aggregation.match(criteria),Aggregation.unwind("orders"),Aggregation.group("buyerNick").first("buyerNick").as("buyerNick").first("mobile").as("mobile").first("address").as("address").sum("payment").as("totalPayment").sum("num").as("itemNum").count().as("orderNum"),Aggregation.sort(new Sort(new Sort.Order(Sort.Direction.DESC, "totalPayment"))),Aggregation.skip(startRows),Aggregation.limit(pageSize));List<CustomerDetail> customerList = tradeRepository.findAggregateList(new Query(criteria), userId, customerAgg,CustomerDetail.class);return customerList;
}
public <T> List<T> findAggregateList(Query query,String userNickName, Aggregation aggregation,Class<T> clazz) {AggregationResults<T> aggregate = this.mongoTemplate.aggregate(aggregation, collectionName, clazz);List<T> customerDetails = aggregate.getMappedResults();return customerDetails;
}

3,三张表在java中实体如何关联的:字表定义为List

@Data
@ToString
public class DocumentEntity extends MongoBaseEntity {/*** 档案名称*/private String name;/*** 档案类型*/private int type;/*** 所属公司*/private Integer companyId;/*** 流水号*/private String serialNum;/*** 档案编号*/private String code;/*** 状态*/private String status;/*** 保密等级*/private String secrecyLevel;/*** 资料数量*/private Long detailNum;/*** 描述*/private String description;/*** 自定义字段 map集合,*/private Map<String,Object> documentMap;/*** 文件集合*/private List<FileEntity> fileList;/*** 发票集合*/private List<InvoiceEntity> InvoiceList;}

mongoTemplate.aggregate() 聚合查询,关联查询相关推荐

  1. springboot集成mongoDB高级聚合查询,关联查询

    目录 mongoDB的常用操作符 mongoDB的聚合管道符号 比较操作符 逻辑运算符? 注意注意注意? 数学运算符 mongoDB案例 ? ? ? ? 插入测试数据 ?mongodb的阶段操作符号 ...

  2. springboot集成mongoDB高级聚合查询,关联查询,lookup.let多条件关联查询。

    目录 mongoDB的常用操作符 mongoDB的聚合管道符号 比较操作符 逻辑运算符 注意坑 数学运算符 mongoDB案例 插入测试数据 mongodb的阶段操作符号 $match: $count ...

  3. mongoTemplate的多表关联查询

    一.使用场景 购物车表-car 购物车中的商品表 需要在查询car表的时候根据carId带出下面关联的商品 二.代码实现 pojo @Data @Document(collection = " ...

  4. Mongoose aggregate 多表关联查询

    1. 查询每个order订单中的所有orderItem(多表关联查询) order.js: var mongoose = require('./db.js')var OrderSchema = mon ...

  5. 318分组聚合,关联查询(多表连接查询)(连接查询),连接查询oracle写法,集合运算ld

    ----------分组聚合:对表里面的数据进行各个维度/角度的统计 -------------统计:需要用 聚合函数 max(目标字段):求最大值 min(目标字段) :求最小值 avg(目标字段) ...

  6. ORM多表查询——关联查询

    一.关联查询: 通过父表参数获取从表数据,通过从表参数获取父表数据 从表查询主表中的数据 附件:数据表截图 项目表  接口表 现在要实现的需求如下: 1.查询项目名称中包含'搜狗'的所属接口信息: 分 ...

  7. java mongodb 多表关联查询,多条件查询,分页,排序

    前言: 由于最近项目赶,版本迭代快,不知道大BOSS从哪里听别人说MongoDB用来做关系型数据库好,而且速度快,性能高:听到这话的我,立马就反驳了回去:"MongoDB不支持事物" ...

  8. 数据库学习day_03:关联关系/ 关联查询/ JDBC

    关联关系 创建表时,表与表之间存在的业务关系 外键: 用来建立关系的字段称为外键 有哪些关系: 一对一:有AB两张表,A表的一条数据对应B表的一条,同时B表的1条也对应A表的一条,称为一对一关系. 如 ...

  9. Day4-Mybatis框架(多表的关联查询)

    Day4-Mybatis框架(多表的关联查询) 关联查询 使用背景:项目中可能不止一个表的时候 即多表的时候(表间关系可分为一对一,一对多,多对多) 这时候查询会涉及到来自多个表的操作. 简单的入门代 ...

  10. MYSQL多表关联查询与子查询

    多表关联查询 关联查询又名连接查询,其主要包括了内连接,外连接,自连接,交叉连接等四个大类. 首先我们要清楚我们为什么要使用多表关联查询,肯定是因为我们想要显示的数据来自于两个或多个数据表内部,我们想 ...

最新文章

  1. 如何用命令将本地项目上传到git
  2. pytorch attention
  3. go语言中变量的定义和使用
  4. Web应用程序体系结构– Spring MVC – AngularJs堆栈
  5. java中什么表示打印_在java中打印对象时会发生什么
  6. 2、Eternal框架-svn_有更新!
  7. java中write方法报错_Java中管道报错:Write end dead
  8. websocket 发送图片_基于WebSocket的web端IM即时通讯应用的开发
  9. 【matlab】在图中插入矩形(框or阴影)
  10. 基于分布式光纤传感的高压电力线路异常监测探讨
  11. 9月1日起施行《中华人民共和国数据安全法》发布(附全文
  12. 网络表情NLP(二)︱特殊表情包+emoji识别
  13. python怎样编程_怎么自学python编程
  14. 如何做到高效沟通和高效沟通的好处
  15. 【算法】计划看电影-java
  16. 重生之我是赏金猎人-漏洞挖掘(十一)-某SRC储存XSS多次BypassWAF挖掘
  17. 桌面云、云桌面的区别
  18. C语言-算术表达式-加,减,乘,除,求余
  19. 苹果挺进“可折叠”手机赛道,柔性屏将迎来大发展
  20. Posts Tagged ‘ionCube Loader is a Zend-Engine extension and not a module’

热门文章

  1. 55. GridPanel中getSelectionModel详解
  2. Coloring Flame Graphs: Code Hues
  3. MySQL日期 专题
  4. linux常用命令之压缩打包
  5. 终于把tomcat给搞定了
  6. 一个较好的基础的数据库连接池知识
  7. 触发C#Button的双击事件
  8. BusyBox 中添加新命令
  9. C语言汇编-函数调用堆栈的过程
  10. w3wp对应进程_认识w3wp.exe进程,从根本上解决占用资源较大问题