spring-data-mongodb 获得记录条数

方法一 . 查询出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;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值