mongodb復(fù)雜條件查詢 (or與and)
參考上篇文章博肋,需要針對mongoDB進行組合查詢,以下代碼示例
public CaseBo searchCase(String caseRootId, String tags, String priorities, Integer taskId) {
if (caseRootId==null || caseRootId.isEmpty()) {
logger.error("caseRootId不能為空");
return null;
}
// 創(chuàng)建新的查詢條件
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.圈選標(biāo)簽
String[] tagList = tags.split(",");
criteria1.and("resource").in(Arrays.asList(tagList));
}
if (StringUtils.isNotEmpty(priorities)) {
//3.圈選優(yōu)先級
List<Integer> 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的關(guān)系
query = new Query(new Criteria().andOperator(criteria, criteria2));
}else if (StringUtils.isEmpty(priorities) && StringUtils.isNotEmpty(tags)){
//and的關(guān)系
query = new Query(new Criteria().andOperator(criteria, criteria1));
}else {
query = new Query(criteria);
}
List<CaseDataBo> selectedCaseInfos = mongoTemplate.find(query, CaseDataBo.class, MongoConstants.CASE2);
logger.info("根據(jù)測試任務(wù)圈選條件查詢用例結(jié)果條數(shù):" + selectedCaseInfos.size());
//5.把所有用例的path信息取出來,把id放入set鹊杖,避免重復(fù)
Set<ObjectId> idSet = getPathIdSet2(selectedCaseInfos);
CaseDataBo caseInfo = getCaseById2(caseRootId);
CaseBo root = new CaseBo();
root.setData(caseInfo);
//6.從根節(jié)點開始構(gòu)建樹沪悲,只構(gòu)建id位于set中的
buildCaseInfo(idSet, root, "," + caseInfo.getId() + ",", taskId);
return root;