Springboot 2.X MongoTemplate 统计查询以及查询部分指定字段


1 摘要

MongoDB 作为 NoSQL 文档数据库,其查询的语法区别于传统的关系型数据库。本文将介绍 MongoTemplate 查询部分指定字段以及统计查询功能。

2 查询指定字段

./demo-mongodb/src/main/java/com/ljq/demo/springboot/mongodb/service/impl/BlogServiceImpl.java
    /**
     * 查询博客阅读量
     *
     * @param readCountQueryParam
     * @return
     */
    @Override
    public ApiResult queryReadCount(BlogReadCountQueryParam readCountQueryParam) {
        // 查询条件
        Criteria criteria = Criteria.where("id").is(readCountQueryParam.getId());
        // 查询字段
        Query query = Query.query(criteria);
        query.fields().include("id", "title", "countRead", "countLike");
        return ApiResult.success(mongoTemplate.findOne(query, BlogEntity.class));
    }
query.fields().include("id", "title", "countRead", "countLike");

用于指定需要查询的字段

3 统计查询

需求: 查询数据的统计信息,如总数据条数、某个字段的求和、某个字段的平均值等

./demo-mongodb/src/main/java/com/ljq/demo/springboot/mongodb/service/impl/BlogServiceImpl.java
    /**
     * 查询博客阅读量统计
     *
     * @param readCountSummaryParam
     * @return
     */
    @Override
    public ApiResult summaryReadCount(BlogReadCountSummaryParam readCountSummaryParam) {
        // 查询条件
        Criteria criteria = new Criteria();
        if (StrUtil.isNotBlank(readCountSummaryParam.getId())) {
            criteria.and("id").is(readCountSummaryParam.getId());
        }
        if (StrUtil.isNotBlank(readCountSummaryParam.getAuthor())) {
            criteria.and("author").is(readCountSummaryParam.getAuthor());
        }
        // 查询条件
        MatchOperation match = Aggregation.match(criteria);
        // 分组统计
        GroupOperation group = Aggregation.group()
                .count().as("totalBlog")
                .sum("countRead").as("totalRead")
                .avg("countRead").as("aveRead")
                .sum("countLike").as("totalLike")
                .avg("countLike").as("aveLike");
        // 查询结果
        AggregationResults<BlogSummaryVo> results = mongoTemplate.aggregate(Aggregation.newAggregation(BlogEntity.class,
                match, group), BlogSummaryVo.class);
        return ApiResult.success(results.getUniqueMappedResult());
    }

org.springframework.data.mongodb.core.aggregation.Aggregation 用于实现复杂的聚合查询

在本需求中是查询所有数据的总条数、总和等功能,不需要指定分组字段,也不需要通过 ProjectionOperation 来指定查询字段。

(PS: 查遍全网,搜到的资料全是按照字段分组查询,我需要的是查询整个表的数据统计,而不是某一个字段或者按日期的分组,无奈,只能自己来写一个示例了)

4 推荐参考资料

springboot使用MongoTemplate分组统计数据

使用mongoTemplate进行Aggregation聚合查询

5 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
404Code

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值