mongoTemplate获取mongodb获取内嵌数组中的子文档

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;
posted @ 2022-02-17 18:29  Materben  阅读(988)  评论(0编辑  收藏  举报