mongoDB分组查询

完整代码

cpp 复制代码
//根据医院编号 和 科室编号 ,查询排班规则数据
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2 根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                .first("workDate").as("workDate")
                //3 统计号源数量
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //4 实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //调用方法,最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //把日期对应星期获取
        for(BookingScheduleRuleVo bookingScheduleRuleVo:bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据,进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);

        return result;
    }
相关推荐
kirs_ur5 小时前
ECC & LDPC — SSD 的数据卫士
服务器·数据库·性能优化
是三一seven6 小时前
Sql注入基础
数据库·安全·网络安全
Sirens.6 小时前
MySQL表设计进阶-约束范式连接索引与事务
android·数据库·mysql
字节跳动开源8 小时前
火山引擎开源 Agent 驱动的搜索自迭代技术
数据库·开源·agent
Oo大司命oO10 小时前
藏在正则表达式里的陷阱
数据库·mysql·正则表达式
_oP_i11 小时前
mysql统计数据库使用存储大小
数据库
会编程的土豆11 小时前
MySQL 入门:库、表、行、主键是什么
linux·数据库·网络协议·http
jjjava2.011 小时前
系统日志:从入门到精通的完整指南
网络·数据库
写代码的强哥11 小时前
云原生数据库与传统数据库相比“新”在哪里
数据库·云原生·架构