mongoTemplate的for循环操作

因为criteria,不能重复添加同一个参数。如下面的printDateStr,在for循环到第二次时,就会报错。

for (String certificateDate : dataList) {
            criteria.and("printDateStr").is(certificateDate);
            query.addCriteria(criteria);
            List<UserCertificatePrintRecordVo> userCertificatePrintRecordVos = mongoTemplate.find(query, UserCertificatePrintRecordVo.class);
            for (UserCertificatePrintRecordVo userCertificatePrintRecordVo : userCertificatePrintRecordVos) {
                classHours += userCertificatePrintRecordVo.getClassScores();
            }
            dataMap.put(certificateDate, classHours);
            classHours = 0.0;
        }

我们可以用Aggregation来解决,如下:

    private Map<String, Object> setUserCertificateTotalClassHours(List<String> dataList) {
        Criteria criteria = new Criteria();
        Map<String, Object> dataMap = new HashMap<>(16);
        double classHours = 0.0;
        for (String certificateDate : dataList) {
// 设置条件
            Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(new Criteria().andOperator(criteria.where("printDateStr").is(certificateDate), criteria))
            );
// 查询
            AggregationResults<UserCertificatePrintRecordVo> carFlowResultVOs = mongoTemplate.aggregate(aggregation,
                    "UserCertificatePrintRecordVo", UserCertificatePrintRecordVo.class);
            List<UserCertificatePrintRecordVo> userCertificatePrintRecordVos = carFlowResultVOs.getMappedResults();
            for (UserCertificatePrintRecordVo userCertificatePrintRecordVo : userCertificatePrintRecordVos) {
                classHours += userCertificatePrintRecordVo.getClassScores();
            }
            dataMap.put(certificateDate, classHours);
            classHours = 0.0;
        }
        return dataMap;
    }

猜你喜欢

转载自blog.csdn.net/Ciel_Y/article/details/122468255
今日推荐