项目中有查询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出想要的答案

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
  • 2022-02-02
  • 2021-07-26
  • 2022-12-23
  • 2021-08-03
  • 2022-12-23
猜你喜欢
  • 2021-06-06
  • 2022-12-23
  • 2021-11-17
  • 2021-05-10
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案