MONGODB03 – 分組計數_分組去重計數(基於 spring-data-mongodb)

前因

項目中有查詢MongoDB單表統計相關功能,涉及到MongoDB數據聚合相關操作,其中在多字段分組去重計數相關操作API上資料較少,spring-data-mongodb相關的API介紹也不夠直給

需求

沒有需求的編碼都是耍流氓,需求有二

  1. 查詢XX的ID下所有任務的數量

  2. 查詢XX的ID下每個用戶對應的任務數

實現

Mysql

這樣的需求在mysql中非常只是非常簡單的兩句查詢

select count(1) as count , medalId from XXTask group by medalId;
select count(distinct userId) as count,medalId from XXTask group by medalId; 

MongoDB

第一個需求比較簡單,採用Aggregation進行數據聚合即可

Criteria criteria = Criteria.where("medalId").in({"id1","id2"});
if (start != null && end != null) {
    criteria.and("submitTime").gte(start).lt(end);
}

/*認證次數數據聚合*/
Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.match(criteria),
        Aggregation.group("medalId").count().as("count").last("medalId").as("medalId")
);
List<AggregationCountPOJO> verifyCounts = mongoTemplate.aggregate(aggregation, MedalTask.class, MedalTaskCount.class).getMappedResults();

第二個需求也比較簡單,也是採用Aggregation進行數據聚合,不過需要稍微轉個彎

Criteria criteria = Criteria.where("medalId").in({"id1","id2"});
if (start != null && end != null) {
    criteria.and("submitTime").gte(start).lt(end);
}

/*認證次數數據聚合*/
Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("medalId", "userId"),
                Aggregation.group("medalId").last("medalId").as("medalId").count().as("count")
);
List<AggregationCountPOJO> verifyCounts = mongoTemplate.aggregate(aggregation, MedalTask.class, MedalTaskCount.class).getMappedResults();

其中第一次按照雙字段分組,第一層group取得medalId和userId的分組信息,第二層group再以medalId為分組對象,則能count出想要的答案

Tags: