mongotemplate使用聚合得到count—Demo
1. document里面有列表,需要查询列表里面的条件
document中有列表查询时需要先将要查询的列表unwind出来,然后查询才是准确的。
UnwindOperation firstStageUnwindOperation = Aggregation.unwind("userRoleList");
UnwindOperation secondStageUnwindOperation = Aggregation.unwind("userRoleList.schoolIds");
MatchOperation matchOperation = Aggregation.match(Criteria.where("userRoleList.schoolIds").is(id).and("status").is(1).and("userRoleList.roleType").is(0));
CountOperation countOperation = Aggregation.count().as("count");
Aggregation aggregation = Aggregation.newAggregation(firstStageUnwindOperation, secondStageUnwindOperation, matchOperation, countOperation);
AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, User.class, Map.class);
return result.getUniqueMappedResult() == null ? 0 : (Integer) result.getUniqueMappedResult().get("count");
一些例子,直接看官方文档吧,懒得写了
官方unwind使用方法
document里面需要分组后统计组数
MatchOperation matchOperation = Aggregation.match(Criteria.where("schoolId").is(school.getId())
.and("knowledgeId").is(knowledgeId)
.and("status").is(3)
.and("areaId").is(areaId).and("finishTime").gte(start).lte(end));
GroupOperation groupOperation = group("userId");
CountOperation countOperation = count().as("count");
Aggregation aggregation = Aggregation.newAggregation(matchOperation,groupOperation,countOperation);
AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, EvalTsinghuaRecord.class, Map.class);
使用几个文档来解释一下
{"userId":1,"roleType":0}
{"userId":2,"roleType":1}
{"userId":1,"roleType":1}
{"userId":1,"roleType":2}
{"userId":3,"roleType":0}
结果1:
{"userId":1, "count":3}
{"userId":2,"count":1}
{"userId":3,"count":1}
结果2:
{"count":3}
getUniqueMappedResult()这个方法可以认为是结果只有一个文档的时候才能用的,最后的结果是多个文档时要使用getMappedResults()方法。