MongoDB之Aggregation 在Java中的使用

    private Map <String,String> getQdBlCountByAnswerId(String[] answerId,String projectTypeCode,String surveyTypeCode) {
        /**
         * 原生sql:
         // 统计 选项是 并联办理手续名称序号 情况
         db.eaa_pd_qc_survey_answer.aggregate([
         { $match : { "answer_id" : { $in : ['1ca2879f43f0f4a9a439ec53af0201d3','d5bba5d33c018bf0ab9fd369e51b9976'] }, "issues_list" : { $ne : null } } },
         { $unwind : "$issues_list" },
         { $unwind : "$issues_list.questions" },
         {$match:{'issues_list.questions.options':{$ne:null,$exists: true}}},
         {$project:{
         "_id": 0,
         "answer_id": 1,
         "issues_list.id": 1,
         "issues_list.questions.id": 1,
         "issues_list.questions.options": 1,
         optionsSize:{$size:"$issues_list.questions.options"},
         groupId: { $concat: [  "$issues_list.id","_","$issues_list.questions.id"]}
         }},
         {$match:{'optionsSize':{$gt:0}}},
         {$group:{_id:'$groupId',qcCount:{$sum:1},answerRe: { $push:  { answer: "$issues_list.questions.options"} }}},
         {$sort:{_id:1}}
         ])
         */
        List<AggregationOperation> operations = new ArrayList<>();
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("answer_id").in(answerId).and("issues_list").ne(null)),
                Aggregation.unwind("issues_list"),
                Aggregation.unwind("issues_list.questions"),
                Aggregation.match(Criteria.where("issues_list.questions.options").exists(true).ne(null)),
                Aggregation.project("answer_id")
                        .and("$issues_list.id").as("one_id")
                        .and("$issues_list.questions.id").as("twoId")
                        .and("$issues_list.questions.options").as("options")
                        .andExpression("{$size:'$issues_list.questions.options'}").as("optionsSize")
                        .andExpression("concat('$issues_list.id','_stc_"+projectTypeCode+"_"+surveyTypeCode+"_','$issues_list.questions.id')").as("groupId"),
                Aggregation.match(Criteria.where("optionsSize").gt(0)),
                Aggregation.group("$groupId").count().as("qcCount").push(new BasicDBObject("answer", "$options")).as("answerResult"),
                Aggregation.sort(Sort.Direction.ASC, "_id")
        );
        AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "eaa_pd_qc_survey_answer", Document.class);
        //将结果封装成map
        int mappedResultsLen = results.getMappedResults().size();
        Map <String,String> map = new HashMap<>();
        if(mappedResultsLen>0){
            for(int i=0;i<mappedResultsLen;i++){
                List answerResultArr = (ArrayList)results.getMappedResults().get(i).get("answerResult");
                int answerResultLen = answerResultArr.size();
                StringBuffer answerBuffer = new StringBuffer();
                StringBuffer stringBuffer = new StringBuffer();
                for(int j = 0;j<answerResultLen;j++){
                    List answerArr = (ArrayList)(((Document)answerResultArr.get(j)).get("answer"));
                    int answerLen = answerArr.size();
                    if(answerLen >0){
                        for(int k = 0; k < answerLen; k++){
                           String answer =  (answerArr.get(k).toString()).replace("pd_","");
                           answerBuffer.append((j+1)).append(".").append((k+1)).append("、").append(answer).append("\n");
                        }
                    }

                }
                stringBuffer.append("共计回答(").append(results.getMappedResults().get(i).get("qcCount").toString())
                        .append(")份,具体内容如下:").append("\n").append(answerBuffer.toString());
                String key = (results.getMappedResults().get(i).get("_id").toString()).replaceAll("-","_");//替换所有的横线为下划线
                map.put(key,stringBuffer.toString());
            }
        }
        return map;
    }
    public Map <String,String> getQdCountByAnswerId(String[] answerId,String projectTypeCode,String surveyTypeCode) {
        /**
         * 原生sql:
             // 统计 选项是 填写内容 和 选项是 选择是的  情况
                //todo 目前无法拼写$switch 语法 没得研究 时间太紧
                 db.eaa_pd_qc_survey_answer.aggregate(
                 [
                 { $match : { "answer_id" : { $in : ['1ca2879f43f0f4a9a439ec53af0201d3','d5bba5d33c018bf0ab9fd369e51b9976'] }, "issues_list" : { $ne : null } } },
                 { $unwind : "$issues_list" },
                 { $unwind : "$issues_list.questions" },
                 {$match:{'issues_list.questions.answer':{$ne:'',$exists: true,$ne:null},
                 $or: [{'issues_list.questions.answer':{$ne:false}}]
                 }},
                 {$project:{
                 "_id": 0,
                 "answer_id": 1,
                 "issues_list.id": 1,
                 "issues_list.questions.id": 1,
                 "issues_list.questions.answer": 1,
                 answerConvert: {
                 $switch:
                 {
                 branches: [
                 {
                 case: { $eq : ['$issues_list.questions.answer', true] },
                 then: { $concat: ["是","\n" ]}
                 },
                 {//因为前面加了 条件筛选 这里可不进行判断
                 case: { $eq : ['$issues_list.questions.answer',false] },
                 then: { $concat: ["否","\n" ]}
                 }
                 ],
                 default:{ $concat: ["$issues_list.questions.answer","\n" ]}
                 }
                 },
                 groupId: { $concat: [  "$issues_list.id","_","$issues_list.questions.id"]}
                 }},
                 {$group:{_id:'$groupId',qcCount:{$sum:1},answerRe: { $push:  { answer: "$answerConvert"} }}},
                 {$sort:{_id:1}}
                 ])


                // 统计手续时间费用表 选项是 填写内容 和 选项是 选择是的  情况 ----目前使用
                 db.eaa_pd_qc_survey_answer.aggregate(
                 [
                 { $match : { "answer_id" : { $in : ['1ca2879f43f0f4a9a439ec53af0201d3','d5bba5d33c018bf0ab9fd369e51b9976'] }, "issues_list" : { $ne : null } } },
                 { $unwind : "$issues_list" },
                 { $unwind : "$issues_list.questions" },
                 {$match:{'issues_list.questions.answer':{$ne:'',$exists: true,$ne:null},
                 $or: [{'issues_list.questions.answer':{$ne:false}}]
                 }},
                 {$project:{
                 "_id": 0,
                 "answer_id": 1,
                 "issues_list.id": 1,
                 "issues_list.questions.id": 1,
                 "answerConvert":{$toString:"$issues_list.questions.answer"},
                 groupId: { $concat: [  "$issues_list.id","_","$issues_list.questions.id"]}
                 }},
                 {$group:{_id:'$groupId',qcCount:{$sum:1},answerRe: { $push:  { answer: "$answerConvert"} }}},
                 {$sort:{_id:1}}
                 ])
         */
        List<AggregationOperation> operations = new ArrayList<>();
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("answer_id").in(answerId).and("issues_list").ne(null)),
                Aggregation.unwind("issues_list"),
                Aggregation.unwind("issues_list.questions"),
                Aggregation.match(Criteria.where("issues_list.questions.answer").exists(true).ne("").ne(null)
                        .orOperator(Criteria.where("issues_list.questions.answer").ne(false))),
                Aggregation.project("answer_id")
                        .and("$issues_list.id").as("one_id")
                        .and("$issues_list.questions.id").as("twoId")
                        .andExpression("{$toString:'$issues_list.questions.answer'}").as("answerStr")
                        .andExpression("concat('$issues_list.id','_stc_"+projectTypeCode+"_"+surveyTypeCode+"_','$issues_list.questions.id')").as("groupId"),
                Aggregation.group("$groupId").count().as("qcCount").push(new BasicDBObject("answer", "$answerStr")).as("answerResult"),
                Aggregation.sort(Sort.Direction.ASC, "_id")
        );
        AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "eaa_pd_qc_survey_answer", Document.class);
        //将结果封装成map
        int mappedResultsLen = results.getMappedResults().size();
        Map <String,String> map = new HashMap<>();
        if(mappedResultsLen>0){
            for(int i=0;i<mappedResultsLen;i++){
                List answerArr = (ArrayList)results.getMappedResults().get(i).get("answerResult");
                int answerLen = answerArr.size();
                StringBuffer answerBuffer = new StringBuffer();
                StringBuffer stringBuffer = new StringBuffer();
                for(int j = 0;j<answerLen;j++){
                    String answer = (((Document)answerArr.get(j)).get("answer")).toString();
                    if(StringUtils.equals(answer,"true")){
                        answerBuffer.append((j+1)).append("、").append("是").append("\n");
                    }else{
                        answerBuffer.append((j+1)).append("、").append(answer).append("\n");
                    }
                }
                stringBuffer.append("共计回答(").append(results.getMappedResults().get(i).get("qcCount").toString())
                        .append(")份,具体内容如下:").append("\n").append(answerBuffer.toString());
                String key = (results.getMappedResults().get(i).get("_id").toString()).replaceAll("-","_");//替换所有的横线为下划线
                map.put(key,stringBuffer.toString());
            }
        }
        Map bl = getQdBlCountByAnswerId(answerId,projectTypeCode,surveyTypeCode);//手续、费用、时间问卷 的并联办理手续名称序号 情况
        map.putAll(bl);
        return map;
    }

你可能感兴趣的:(mongoDB)