在java中使用MongoTemplate聚合操作MongoDB

参考链接:(  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 outputType=mongoTemplate.aggregate(agg,"test",Test.class);    
    List list=outputType.getMappedResults(); 

 

或者处理结果:
AggregationResults result = mongoTemplate.aggregate(agg,tableName, Document.class);
result.getMappedResults().forEach(document ->{
  Map map = new HashMap();
   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);
});

 

你可能感兴趣的:(在java中使用MongoTemplate聚合操作MongoDB)