在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