spring-data-mongodb 获得记录条数

来源:互联网 发布:充电器不拔的危害 知乎 编辑:程序博客网 时间:2024/06/04 01:18

方法一 . 查询出list然后获取size,当记录条数多的时候这个方案不可取...


方法二 . 使用mongoTemplate.count查询出记录条数


方法三 . 使用Aggregation,聚合出记录条数

private int getOrderSize(Criteria matchStatus) {        Aggregation aggregate =  Aggregation.newAggregation(                matchStatus,                Aggregation.group("_id").count().as("count")        );        AggregationResults<HostingCount> aggregateResult = mongoTemplate.aggregate(aggregate, collectionName, HostingCount.class);        return GetAggregationSize.getSize(aggregateResult);    }

public class HostingCount {    private String hosting;    private long total;    public HostingCount(String hosting, long total) {        this.hosting = hosting;        this.total = total;    }    public HostingCount() {    }    public String getHosting() {        return hosting;    }    public void setHosting(String hosting) {        this.hosting = hosting;    }    public long getTotal() {        return total;    }    public void setTotal(long total) {        this.total = total;    }}

public class GetAggregationSize {    public static int getSize(AggregationResults aggregateResult){        if (aggregateResult!=null) {            BasicDBList basicDBList = (BasicDBList) aggregateResult.getRawResults().get("result");            if(basicDBList.size()==0) {                {                    return 0;                }            }            long count = 0;            for(Object object:basicDBList){                Map map = (Map) object;                count += Integer.parseInt(map.get("count").toString());            }            return Integer.parseInt(String.valueOf(count));        }        return 0;    }}





原创粉丝点击