SpringBoot连接MongoDB(单节点)

pom.xml(SpringBoot版本1.5.9)

        <!-- 集成mongodb -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

配置文件

#mongodb配置
spring:
  data:
    mongodb:
      host: ip
      port: port
      database: ismart

分页查询

    @Autowired
    private MongoTemplate mongoTemplate;

    public void demo01() {
        Criteria c = new Criteria();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                c.and(entry.getKey()).is(entry.getValue());
            }
        }
        /**
         * (num-1) * pageSize
         * 1 10 0 10
         * 2 10 10 10
         * 3 10 20 10
         */
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        List<ReadingHistory> data = mongoTemplate.find(Query.query(c)
                        .with(new Sort(Sort.Direction.DESC, "mdbCreatedAt")) // 排序
                        .skip((pageNum - 1) * pageSize) //当前页
                        .limit(pageSize), // 每页条数
                ReadingHistory.class, "collectionHistory");
    }

聚合查询-根据时间分组、排序

    数据结构如下图

image.png
  public void count() {
        // 根据部门和时间统计上传图片数量,时间倒序
        Aggregation agg = Aggregation.newAggregation(
//                Aggregation.match(Criteria.where("moduleId").is("ismart")),
                Aggregation.project("moduleId")
                        .and(DateOperators.DateToString.dateOf("createTime")
                                .toString("%Y-%m-%d")).as("date"),
                Aggregation.group("date","moduleId").count().as("total"),
                Aggregation.sort(Sort.Direction.DESC, "date","moduleId")
        );

        // 输出数据
        AggregationResults<JSONObject> a = mongoTemplate.aggregate(agg, "fastdfs", JSONObject.class);
        System.out.println(a);
        List<JSONObject> list = a.getMappedResults();
        for (JSONObject count : list) {
            System.out.println(count.toString());
        }
    }
      输出结果如下:
      {"date":"2019-04-11","total":2,"moduleId":"ismart"}
      {"date":"2019-04-11","total":750,"moduleId":"industrial"}
      {"date":"2019-04-10","total":1239,"moduleId":"ismart"}
      {"date":"2019-04-10","total":973,"moduleId":"industrial"}
      {"date":"2019-04-08","total":1367,"moduleId":"ismart"}
      {"date":"2019-04-08","total":2080,"moduleId":"industrial"}
      ...
image.png
  • 需注意SpringBoot版本问题。使用1.5.9.RELEASE版本聚合查询一直报错(如上图),解决方案:升级SpringBoot版本至1.5.10.RELEASE

聚合语法参考:

SQL 操作/函数 mongodb聚合操作
where $match
group by $group
having $match
select $project
order by $sort
limit $limit
sum() $sum
count() $sum
join $lookup(v3.2 新增)

借鉴文章如下:
mongodb高级聚合查询

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容