在SPRING DATA MONGODB中使用聚合统计查询

原文地址:http://blog.****.net/u010084868/article/details/52622938

[java] view plain copy
  1. </pre><p>在SQL语句中如要做统计一般是这种方式</p><p></p><pre name="code" class="sql">SELECT ..,SUM(1)  
  2. FROM ..  
  3. WHERE ..  
  4. GROUP BY ..  
  5. HAVING ..  
  6. SORT ..  

在MONGODB中的架构图:

在SPRING DATA MONGODB中使用聚合统计查询在SPRING DATA MONGODB中使用聚合统计查询在SPRING DATA MONGODB中使用聚合统计查询


在SPRING DATA MONGODB中是这样写的:

[java] view plain copy
  1. public class VideoRepositoryImpl implements VideoRepositoryCustom{  
  2.       
  3.     private static Logger logger = LoggerFactory.getLogger(VideoRepositoryImpl.class);  
  4.       
  5.     @Autowired  
  6.     private MongoTemplate mongoTemplate;  
  7.       
  8.   
  9.   
  10.     public List<Cat1UpdateCount> getVideoWithUpdateFrag(List<String> importantCat1List) {  
  11.           
  12.         logger.info(new Date().toString());  
  13.           
  14.         /** 
  15.          * db.videos.aggregate( 
  16.             [ 
  17.                { $match: { "frags.isnew" : true } }, 
  18.                { $unwind: "$frags" }, 
  19.                { $match: { "frags.isnew" : true } }, 
  20.                { $group: {  
  21.                            _id: {cat1:"$cat1"}, 
  22.                            count: { $sum: 1 }, 
  23.                            publishdate2: { $max: "$publishdate"} 
  24.                          } 
  25.                } 
  26.                 
  27.             ] 
  28.             ) 
  29.          */  
  30.         Aggregation agg = newAggregation(  
  31.                 project("frags","cat1","publishdate"),//挑选所需的字段  
  32.                 match(  
  33.                         Criteria.where("frags.isnew").is(Boolean.TRUE)  
  34.                         .and("cat1").in(importantCat1List)  
  35.                      ),//筛选符合条件的记录  
  36.                 unwind("frags"),//如果有MASTER-ITEM关系的表,需同时JOIN这两张表的,展开子项LIST,且是内链接,即如果父和子的关联ID没有的就不会输出  
  37.                 match(Criteria.where("frags.isnew").is(Boolean.TRUE)),  
  38.                 group("cat1")//设置分组字段  
  39.                     .count().as("updateCount")//增加COUNT为分组后输出的字段  
  40.                     .last("publishdate").as("publishDate"),//增加publishDate为分组后输出的字段  
  41.                 project("publishDate","cat1","updateCount")//重新挑选字段  
  42.                     .and("cat1").previousOperation()//为前一操作所产生的ID FIELD建立别名  
  43.             );  
  44.   
  45.   
  46.             AggregationResults<Cat1UpdateCount> results = mongoTemplate.aggregate(agg, Video.COLLECTION_NAME, Cat1UpdateCount.class);  
  47.             List<Cat1UpdateCount> cat1UpdateCountList = results.getMappedResults();  
  48.           
  49.         return cat1UpdateCountList;  
  50.     }  
  51.   
  52.   
  53. }  


其中frags的数据类型是LIST


Cat1UpdateCount.java

[html] view plain copy
  1. import java.io.Serializable;  
  2.   
  3.   
  4. public class Cat1UpdateCount implements Serializable{  
  5.   
  6.   
  7.     private static final long serialVersionUID = 4240876746984930098L;  
  8.       
  9.     private String cat1;  
  10.       
  11.     private int updateCount;  
  12.       
  13.     private String publishDate;  
  14.   
  15.   
  16.     public String getCat1() {  
  17.         return cat1;  
  18.     }  
  19.   
  20.   
  21.     public void setCat1(String cat1) {  
  22.         this.cat1 = cat1;  
  23.     }  
  24.   
  25.   
  26.     public int getUpdateCount() {  
  27.         return updateCount;  
  28.     }  
  29.   
  30.   
  31.     public void setUpdateCount(int updateCount) {  
  32.         this.updateCount = updateCount;  
  33.     }  
  34.   
  35.   
  36.     public String getPublishDate() {  
  37.         return publishDate;  
  38.     }  
  39.   
  40.   
  41.     public void setPublishDate(String publishDate) {  
  42.         this.publishDate = publishDate;  
  43.     }  
  44.   
  45.   
  46.     public String toString() {  
  47.         return "Cat1UpdateCount [cat1=" + cat1 + "updateCount=" + updateCount  
  48.                 + ", publishDate=" + publishDate + "]";  
  49.     }  
  50.   
  51. }  


案例:

[java] view plain copy
  1. public class ForbiddingUser {  
  2.     private long uid;  
  3.     private Date deadline;  
  4.   
  5.     public long getUid() {  
  6.         return uid;  
  7.     }  
  8.   
  9.     public ForbiddingUser setUid(long uid) {  
  10.         this.uid = uid;  
  11.         return this;  
  12.     }  
  13.   
  14.     public Date getDeadline() {  
  15.         return deadline;  
  16.     }  
  17.   
  18.     public ForbiddingUser setDeadline(Date deadline) {  
  19.         this.deadline = deadline;  
  20.         return this;  
  21.     }  
  22. }  

[java] view plain copy
  1. public List<ForbiddingUser> findForbiddingUserId(String scopeCode, long tenant) {  
  2.         String collectionName = mongoOperations.getCollectionName(UserRecord.class);  
  3.   
  4.         Aggregation aggregation = newAggregation(  
  5.                 match(where("deadline").gt(new Date())  
  6.                         .and("tenant").is(tenant)  
  7.                         .and("scopeCode").is(scopeCode)),  
  8.                 project("uid""deadline")  
  9.         );  
  10.         AggregationResults<ForbiddingUser> results = mongoOperations.aggregate(  
  11.                 aggregation, collectionName, ForbiddingUser.class);  
  12.         return results.getMappedResults();  


案例:

[java] view plain copy
  1. @Override  
  2.    public int countForbidUserAmount(Date begin, Date end, Set<String> scopeCodes, long tenant) {  
  3.        Aggregation aggregation = newAggregation(  
  4.                match(where("tenant").is(tenant)  
  5.                        .and("scopeCode").in(scopeCodes)  
  6.                        .andOperator(where("time").gte(begin),  
  7.                                where("time").lte(end))),  
  8.                project("uids"),  
  9.                unwind("uids"),  
  10.                group("uids"),  
  11.                MongoUtils.aggregationCount()  
  12.        );  
  13.        AggregationResults<Map> results = mongoOperations.aggregate(  
  14.                aggregation, getForbidCollection(), Map.class);  
  15.        return MongoUtils.parseAggregationCount(results);  
  16.    }