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: