在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<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);
});

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM