Java代码实现MongoDB数据聚合查询

Java代码实现Mongo数据聚合查询

首先引入mongo依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>
  1. 俩张mongo数据库表进行联查
			// java实现'from'后面是副表名,‘localField’:主表关联字段,‘foreignField’:副表关联字段,‘as’:关联表的命名,score1相当于临时集合存储数据
            LookupOperation lookupOperation = LookupOperation.newLookup().from("test_study_log").
            localField("userId").foreignField("userId").as("score1");
            //上面的关联查询只是两张表进行关联,如果想要一对多,就再创建一个LookupOperation对象,将对象添加到List集合中即可实现。
            // 拼装具体查询信息
            Criteria docCri = Criteria.where("score1").not().size(0);
            docCri.and("totalLength").is(100);//条件1
            docCri.and("videoName").is("测试课程");//条件2
            AggregationOperation match = Aggregation.match(docCri);
            // 把条件封装成List
            List operations = new ArrayList<>();
            operations.add(lookupOperation);
            operations.add(match);
            // 构建 Aggregation
            Aggregation aggregation = Aggregation.newAggregation(operations);
            // 执行查询
            AggregationResults results = mongoTemplate.aggregate(aggregation, "video_store", Map.class);
            List mapList = results.getMappedResults();
            System.err.println("联查结果:"+ JSON.toJSONString(mapList));

2、分页查询处理 (ps:PageHelper分页组件使用项目环境内的就行)

			Map resultMap = new HashMap<>();
            int currentPage = 1;
            int pageSize = 5;
            PageHelper.startPage(currentPage,pageSize);
            //模糊查询 模糊匹配
            //Pattern pattern = Pattern.compile("^.*"+"s"+".*",Pattern.CASE_INSENSITIVE);
            //Query query = Query.query(Criteria.where("provinceCode").regex(pattern));
            Query query = new Query();
            // 查询记录总数
            int totalCount = (int) mongoTemplate.count(query, Map.class,"test_study_log");
            // 数据总页数
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            // 设置记录总数和总页数
            resultMap.put("totalCount", totalCount);
            resultMap.put("totalPage", totalPage);
            // 设置起始数
            query.skip((currentPage - 1) * pageSize)
            // 设置查询条数
            .limit(pageSize);
            // 排序
            query.with(Sort.by(Sort.Direction.DESC,"createTime"));
            // 查询当前页数据集合
            List records = mongoTemplate.find(query, Map.class,"test_study_log");
            PageInfo<Map> pageRecords = new PageInfo<>(records);
            System.err.println("分页查询结果:"+ JSON.toJSONString(pageRecords));

3、聚合分组查询

			//写法1
            List operations2 = new ArrayList<>();
            operations2.add(Aggregation.group("userId").first("userId").as("userId").count().as("totalLength"));
            operations2.add(Aggregation.project("userId","totalLength").andExclude("_id"));
            Aggregation aggregation2 = Aggregation.newAggregation(operations2);
            AggregationResults map = mongoTemplate.aggregate(aggregation2,"test_study_log",TestStudyPo.class);
            List list = map.getMappedResults();
            //正序排序
            List mapList1 = (List) list.stream().sorted(Comparator.comparing(TestStudyPo::getUserId)).collect(Collectors.toList());
            mapList1.forEach(map1 -> System.err.println("写法1聚合正序:"+map1));
            //倒序排序
            Collections.sort(mapList1, Comparator.comparing(TestStudyPo::getUserId).reversed());
            mapList1.stream().limit(5).forEach(map1 -> System.err.println("写法1聚合倒序:"+map1));
            System.err.println("聚合分组写法1查询结果:"+ JSON.toJSONString(list));

            //写法2
            AggregationResults<TestStudyPo> document = null;
            document = mongoTemplate.aggregate(Aggregation.newAggregation(
                    //group分组字段 first 需要查询出来的字段 count 合计出来的数字别称
                    Aggregation.group("userId").first("userId").as("userId").count().as("totalLength"),
                    //忽略查询出来后结果集内有_id 避免实例化失败
                    Aggregation.project("userId","totalLength").andExclude("_id")),
                    "test_study_log", TestStudyPo.class);
            List list2 = document.getMappedResults();
            //正序排序
            List mapList2 = (List) list2.stream().sorted(Comparator.comparing(TestStudyPo::getUserId)).collect(Collectors.toList());
            mapList2.forEach(map1 -> System.err.println("聚合正序:"+map1));
            //倒序排序
            Collections.sort(mapList2, Comparator.comparing(TestStudyPo::getUserId).reversed());
            mapList2.stream().limit(5).forEach(map1 -> System.err.println("聚合倒序:"+map1));
            System.err.println("聚合分组写法2查询结果:"+ JSON.toJSONString(list2));

4、聚合合计查询

			List operations3 = new ArrayList<>();
            operations3.add(Aggregation.group("userId").first("userId").as("userId").sum("totalLength").as("totalLength"));
            operations3.add(Aggregation.project("userId","totalLength").andExclude("_id"));
            Aggregation aggregation3 = Aggregation.newAggregation(operations3);
            AggregationResults map3 = mongoTemplate.aggregate(aggregation3,"test_study_log",TestStudyPo.class);
            List<TestStudyPo> list3 = map3.getMappedResults();
            System.err.println("聚合合计查询结果:"+ JSON.toJSONString(list3));

现阶段使用有这些方法,如有需要可借鉴,欢迎补充。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yangyang_VV

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值