当前位置:   article > 正文

Java代码实现MongoDB数据聚合查询_java mongo聚合获取最后结果

java mongo聚合获取最后结果

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

首先引入mongo依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>
  • 1
  • 2
  • 3
  • 4
  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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/56028
推荐阅读
相关标签
  

闽ICP备14008679号