参考链接:( https://blog.csdn.net/baidu_38990811/article/details/80095495 )
Aggregation agg = Aggregation.newAggregation( Aggregation.match(criteria),//条件 Aggregation.group("a","b","c","d","e").count().as("f"),//分组字段 Aggregation.sort(sort),//排序 Aggregation.skip(page.getFirstResult()),//过滤 Aggregation.limit(pageSize)//页数 ); AggregationResults<Test> outputType=mongoTemplate.aggregate(agg,"test",Test.class); List<Test> list=outputType.getMappedResults();
或者处理结果:
AggregationResults<Document> result = mongoTemplate.aggregate(agg,tableName, Document.class); result.getMappedResults().forEach(document ->{ Map<String, Object> map = new HashMap<String, Object>(); for (String key : document.keySet()) { if ("_id".equals(key)) { map.put("_id", document.get("_id").toString()); }else { map.put(key, document.get(key)); } } resultList.add(map); });