zoukankan      html  css  js  c++  java
  • 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; }
  • 相关阅读:
    Android框架之高速开发框架xUtil
    树状数组 LA 4329 亚洲赛北京赛区题
    Linq To Sql 增改删
    标题栏显示进度条
    android:inputType参数类型说明
    Illegal resource reference: @*android resources are private and not always present
    android:editable is deprecated: Use an <EditText> to make it editable
    android:contentDescription的作用是什么
    Replace
    图片缓存优化
  • 原文地址:https://www.cnblogs.com/xiaoliu66007/p/14294384.html
Copyright © 2011-2022 走看看