JSONObject res = null;
//封裝對象列表查詢條件
List<AggregationOperation> commonOperations = new ArrayList<>();
//1. 指定查詢主文檔
MatchOperation match = Aggregation.match(Criteria.where("examCode").is(processCode));
commonOperations.add(match);
//2. 指定投影,返回哪些字段
ProjectionOperation project = Aggregation.project("questions");
commonOperations.add(project);
//3. 拆分內嵌文檔
UnwindOperation unwind = Aggregation.unwind("questions");
commonOperations.add(unwind);
//4. 指定查詢子文檔
MatchOperation match2 = Aggregation.match(
Criteria.where("questions.code").is(questionCode));
commonOperations.add(match2);
//創建管道查詢對象
Aggregation aggregation = Aggregation.newAggregation(commonOperations);
AggregationResults<JSONObject> reminds = mongoTemplate
.aggregate(aggregation, COLLECTION_NAME, JSONObject.class);
List<JSONObject> mappedResults = reminds.getMappedResults();
if (mappedResults != null && mappedResults.size() > 0) {
res = JSONObject
.parseObject(mappedResults.get(0).getJSONObject("questions").toJSONString(), JSONObject.class);
}
return res;