• pring boot mongo分组查询结果总数。总记录数


     方法1:

        protected Long getCountByTime(Long startTime, Long endTime) {
            Criteria criteria = Criteria.where("uptime").gte(startTime).lte(endTime);
            AggregationOptions.Builder builder = new AggregationOptions.Builder().allowDiskUse(true);
            AggregationOptions aggregationOptions = builder.build();
     
            TypedAggregation<Result> agg = Aggregation.newAggregation(Result.class,
                    Aggregation.match(criteria),
                    Aggregation.group("name"),           // 按字段 name 进行分组查询
                    Aggregation.count().as("count"),     // 将结果记录写到 count字段
                    Aggregation.project("count")         // 结果只返回count
     
            ).withOptions(aggregationOptions);
     
            AggregationResults<Result> aggregate = mongoTemplate.aggregate(agg, Record.class, Result.class);
            List<ImsiRegionalStatic> mappedResults = aggregate.getMappedResults();
     
            if (CollectionUtils.isNotEmpty(mappedResults)) {
                return mappedResults.get(0).getCount();
            }else {
                return 0L;
            }
        }

     方法2:下面方法比较通用,上面方法只使用与mongo 3.4.2+ 的版本

    public Map<String, Object> globalSearchMsg(Message msg, List<String> grouIds, Long beginTime, Long endTime, Integer pageNum, Integer pageSize) {
            
            String collectionName = "aaa";
    
            Criteria criteria = new Criteria();
            criteria.and("convType").is(msg.getConvType());
    
            Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(criteria),
                    Aggregation.sort(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime"))),
                    Aggregation.skip((pageNum - 1) * pageSize),
                    Aggregation.limit(pageSize)
            );
            List<DBObject> list = this.mongoTemplate().aggregate(aggregation, collectionName, DBObject.class).getMappedResults();
    Query query = new Query(criteria); Long totalNum = mongoTemplate().count(query, collectionName); int total = totalNum.intValue(); Map<String, Object> mapResult = new HashMap<>(16); mapResult.put("data", list); mapResult.put("total", total); return mapResult; }
  • 相关阅读:
    komodo install on ubuntu
    关于scrapbook的导入导出
    hg常用命令小记

    在cygwin使用python
    命运多cuai
    常用shell命令
    360做电视广告了
    ubuntu im安装
    ubuntu下的路径
  • 原文地址:https://www.cnblogs.com/xiaoliu66007/p/14294384.html
Copyright © 2020-2023  润新知