mongo分组查询,统计 Group.grouping(),Group.first(),Accumulator(“$sum“, new Integer(1) 含义解释

同一个接口,两种方法,结果相同。

1.mongoTemplate

  /**
     * 文章阅读排行榜
     *
     * @param platformId
     * @return
     */
    public Map<String, Integer> getPharamacistArticleStudyRank(String platformId) {
        Map<String, Integer> dataMap = new HashMap<String, Integer>(16);
        Integer studyYear = LmsConfig.getRealStudyYear();
        String pharmacistStudyYearPeriod = LmsConfig.getPharmacistStudyYearPeriod(studyYear);
        String[] pharmacistStudyYear = pharmacistStudyYearPeriod.split("#");
        String startDate = pharmacistStudyYear[0];
        String endDate = pharmacistStudyYear[1];
        // 查询条件
        MatchOperation matchOperation = Aggregation.match(Criteria.where("createTime")
                .gte(DateUtil.getDate(startDate, DateUtil.SECONDFORMAT))
                .lte(DateUtil.getDate(endDate, DateUtil.SECONDFORMAT))
                .and("platformId").is(platformId));
        // 分组条件:按articleId分组,并统计每个分组的数据条数存储到studyYear中
        GroupOperation groupOperation = Aggregation.group("articleId")
                .count().as("studyYear");
        // 查询
        Aggregation agg = Aggregation.newAggregation(matchOperation, groupOperation);
        AggregationResults<PharmacistArticleVo> groupResults = mongoTemplate.aggregate(agg,
                "PharmacistArticleVo", PharmacistArticleVo.class);
        List<PharmacistArticleVo> pharmacistUserPointResults = groupResults.getMappedResults();
        for (PharmacistArticleVo pharmacistArticleVo : pharmacistUserPointResults) {
            dataMap.put(pharmacistArticleVo.getId(), pharmacistArticleVo.getStudyYear());
        }
        return dataMap;
    }
Aggregation agg = Aggregation.newAggregation(    
            Aggregation.match(criteria),//条件  
            Aggregation.group("a","b","c","d","e").count().as("f"),//分组字段    
            Aggregation.sort(sort),//排序  
            Aggregation.skip(page.getFirstResult()),//过滤  
            Aggregation.limit(pageSize)//页数  
         );    
    AggregationResults<Test> outputType=mongoTemplate.aggregate(agg,"test",Test.class);    
    List<Test> list=outputType.getMappedResults();

2.Morphia

   /**
     * 文章阅读排行榜
     * @param platformId
     * @return
     */
    public Map<String, Integer> getPharamacistArticleStudyRank(String platformId) {
        Map<String, Integer> dataMap = new HashMap<String, Integer>();
        Datastore datastore = pharmacistArticleDao.getDatastore();
        Query<PharmacistArticleVo> query = datastore.createQuery(PharmacistArticleVo.class);
        query.field("platformId").equal(platformId);

		Integer studyYear  = SystemConfig.getRealStudyYear();
		String pharmacistStudyYearPeriod = SystemConfig.getPharmacistStudyYearPeriod(studyYear);
		String[] pharmacistStudyYear = pharmacistStudyYearPeriod.split("#");
		String startDate = pharmacistStudyYear[0];
		String endDate = pharmacistStudyYear[1];
        query.filter("createTime >=", DateUtil.getDate(startDate,DateUtil.SECONDFORMAT));
        query.filter("createTime <=",DateUtil.getDate(endDate,DateUtil.SECONDFORMAT));

        AggregationOptions build = AggregationOptions.builder().outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();
        AggregationPipeline pipeline = datastore.createAggregation(PharmacistArticleVo.class).match(query).group(
// 通过articleId进行分类查询得到分组
            Group.id(Group.grouping("articleId")), Group.grouping("articleId", Group.first("articleId")),
// 统计每个分组的数据条数存储到studyYear中
            Group.grouping("studyYear", Group.first("studyYear")), Group.grouping("count", new Accumulator("$sum", new Integer(1))));
// 查询
        Iterator<PharmacistUserPointResult> iterator = pipeline.aggregate(PharmacistUserPointResult.class, build);
        while (iterator.hasNext()) {
            PharmacistUserPointResult result = iterator.next();
            if (result.getArticleId() == null) {
                continue;
            }
            dataMap.put(result.getArticleId(), result.getCount());
        }
        return dataMap;
    }

结果:

他们结果相同,如下:

 结合查询条件和分组条件,和计数条件对应数据库看:

方法含义介绍:

下面两句代码实现相同功能:

// 按userId分组,并将它在返回结果中,以id的形式存储。并统计每个分组的数据条数,存储到返回结果的userId中。如下图所示:
GroupOperation groupOperation = Aggregation.group("userId").count().as("userId");

// 按userId进行分组,并在返回结果中,把它作为id进行存储。
 AggregationPipeline pipeline = datastore.createAggregation(GetPointDayVo.class).match(query).group(Group.id(Group.grouping("userId")),
// 统计每个分组中数据个数,并在返回结果中,把它作为count进行存储。
            Group.grouping("userId", Group.first("userId")), Group.grouping("count", new Accumulator("$sum", new Integer(1))));

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值