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; }

 

posted @ 2021-01-18 18:35  君子笑而不语  阅读(975)  评论(0编辑  收藏  举报