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; }
  • 相关阅读:
    visualStudio 无法登陆
    Roslyn NameSyntax 的 ToString 和 ToFullString 的区别
    Roslyn NameSyntax 的 ToString 和 ToFullString 的区别
    C# Span 入门
    C# Span 入门
    win10 uwp 使用 asp dotnet core 做图床服务器客户端
    win10 uwp 使用 asp dotnet core 做图床服务器客户端
    求点集的外接矩形
    PHP link() 函数
    PHP is_writeable() 函数
  • 原文地址:https://www.cnblogs.com/xiaoliu66007/p/14294384.html
Copyright © 2011-2022 走看看