mongoTemplate 实现聚合查询小记录

179 阅读1分钟

这次是为了记录 通过 mongoTemplate 实现聚合查询的代码片段,设置通过某个字段聚合查询 并返回指定的字段

代码入下

Set<Object> branchTypeSet = new HashSet<>();

try{
    NaviActJudgeTaskEntity taskEntity = getJudgeTaskById(taskId);
    if(Objects.isNull(taskEntity)){
        logger.error("getBranchTypeOldList,taskId有误:{}",taskId);
        throw new RuntimeException("taskId有误");
    }

    String tableName = getTableName(taskEntity);
    String branchType = "old".equals(type) ? "branchtype_old" : "branchtype_new";
    Aggregation aggregation = Aggregation.newAggregation(
    
            //查询条件
            Aggregation.match(new Criteria().where(branchType).ne("").ne(null)),
            
            //聚合字段
            Aggregation.group(branchType),
            
            //只返回当前字段
            Aggregation.project(branchType));
    AggregationResults<JSONObject> results = mongoDBConfig.mongoTemplate().aggregate(aggregation, tableName, JSONObject.class);
    List<JSONObject> mappedResults = results.getMappedResults();
    for (JSONObject result : mappedResults) {
        branchTypeSet.add(result.get("_id"));
    }
}catch (Exception e){
    logger.error("获取岔路口类型下拉列表错误:{}",e.getMessage());
    e.printStackTrace();
}

return branchTypeSet;

返回结果

image.png