1. 程式人生 > >在SPRING DATA MONGODB中使用聚合統計查詢(Java)

在SPRING DATA MONGODB中使用聚合統計查詢(Java)

public class VideoRepositoryImpl implements VideoRepositoryCustom{
    
    private static Logger logger = LoggerFactory.getLogger(VideoRepositoryImpl.class);
    
    @Autowired
    private MongoTemplate mongoTemplate;
    

    public List<Cat1UpdateCount> getVideoWithUpdateFrag(List<String> importantCat1List) {
        
        logger.info(new
 Date().toString());
        
        /**
         * db.videos.aggregate(
            [
               { $match: { "frags.isnew" : true } },
               { $unwind: "$frags" },
               { $match: { "frags.isnew" : true } },
               { $group: { 
                           _id: {cat1:"$cat1"},
                           count: { $sum: 1 },
                           publishdate2: { $max: "$publishdate"}
                         }
               }
               
            ]
            )
         
*/
        Aggregation agg = newAggregation(
                project("frags","cat1","publishdate"),//挑選所需的欄位                match(
                        Criteria.where("frags.isnew").is(Boolean.TRUE)
                        .and("cat1").in(importantCat1List)
                     ),//篩選符合條件的記錄                unwind("frags"),//
如果有MASTER-ITEM關係的表,需同時JOIN這兩張表的,展開子項LIST,且是內連結,即如果父和子的關聯ID沒有的就不會輸出                match(Criteria.where("frags.isnew").is(Boolean.TRUE)),
                group("cat1")//設定分組欄位                    .count().as("updateCount")//增加COUNT為分組後輸出的欄位                    .last("publishdate").as("publishDate"),//增加publishDate為分組後輸出的欄位                project("publishDate","cat1","updateCount")//重新挑選欄位                    .and("cat1").previousOperation()//為前一操作所產生的ID FIELD建立別名            );

            AggregationResults<Cat1UpdateCount> results = mongoTemplate.aggregate(agg, Video.COLLECTION_NAME, Cat1UpdateCount.class);
            List<Cat1UpdateCount> cat1UpdateCountList = results.getMappedResults();
        
        return cat1UpdateCountList;
    }

}