【java】实现mongoDB复制查询条件

mongodb复杂条件查询 (or与and)

参考上篇文章,需要针对mongoDB进行组合查询,以下代码示例

    public CaseBo searchCase(String caseRootId, String tags, String priorities, Integer taskId) {
        if (caseRootId==null || caseRootId.isEmpty()) {
            logger.error("caseRootId不能为空");
            return null;
        }
        // 创建新的查询条件
        Criteria criteria = new Criteria();
        Criteria criteria1 = new Criteria();
        Criteria criteria2 = new Criteria();

        // 1.先找出所有用例CaseInfoList
        String pathRegex = "^," + caseRootId + ".*"; //左匹配
        criteria.and("path").regex(pathRegex);

        if (StringUtils.isNotEmpty(tags)) {
            //2.圈选标签
            String[] tagList = tags.split(",");
            criteria1.and("resource").in(Arrays.asList(tagList));
        }
        if (StringUtils.isNotEmpty(priorities)) {
            //3.圈选优先级
            List priorityIntList = new ArrayList<>();
            String[] priorityList = priorities.split(",");
            for (String priority : priorityList){
                if (priority.equals(CasePriorityEnum.urgent.getPriority())){
                    priorityIntList.add(1);
                }
                if (priority.equals(CasePriorityEnum.high.getPriority())){
                    priorityIntList.add(2);
                }
                if (priority.equals(CasePriorityEnum.medium.getPriority())){
                    priorityIntList.add(3);
                }
                if (priority.equals(CasePriorityEnum.low.getPriority())){
                    priorityIntList.add(4);
                }
            }

            criteria2.and("priority").in(priorityIntList);
        }
        //4.判断查询条件
        Query query = null;
        if (StringUtils.isNotEmpty(priorities) && StringUtils.isNotEmpty(tags)) {
        //外层是or条件,里层是and条件
            query = new Query(new Criteria().orOperator((new Criteria().andOperator(criteria, criteria1)), (new Criteria().andOperator(criteria, criteria2))));
        }else if (StringUtils.isNotEmpty(priorities) && StringUtils.isEmpty(tags)){
        //and的关系
            query = new Query(new Criteria().andOperator(criteria, criteria2));
        }else if (StringUtils.isEmpty(priorities) && StringUtils.isNotEmpty(tags)){
        //and的关系
            query = new Query(new Criteria().andOperator(criteria, criteria1));
        }else {
            query = new Query(criteria);
        }
        List selectedCaseInfos = mongoTemplate.find(query, CaseDataBo.class, MongoConstants.CASE2);
        logger.info("根据测试任务圈选条件查询用例结果条数:" + selectedCaseInfos.size());

        //5.把所有用例的path信息取出来,把id放入set,避免重复
        Set idSet = getPathIdSet2(selectedCaseInfos);
        CaseDataBo caseInfo = getCaseById2(caseRootId);
        CaseBo root = new CaseBo();
        root.setData(caseInfo);
        //6.从根节点开始构建树,只构建id位于set中的
        buildCaseInfo(idSet, root, "," + caseInfo.getId() + ",", taskId);
        return root;

你可能感兴趣的:(【java】实现mongoDB复制查询条件)