SpringBoot集成MongoDB

不问归期 提交于 2020-04-07 14:54:55

前言

之前写了各种nosql数据库的比较,以及相关理论,现在我在本地以springboot+MongoDB框架,探究了具体的运行流程,下面总结一下,分享给大家。

 

运行前准备

安装并启动MongoDB应用程序

参考网址:

windows

http://www.runoob.com/mongodb/mongodb-window-install.html

linux

http://www.runoob.com/mongodb/mongodb-linux-install.html

 

在MongoDB应用工具中查询数据增删改效果(rebo3t)

下载地址:https://robomongo.org/download

 

lombok安装

参考网址:https://www.cnblogs.com/fqszywz/p/7733703.html

 

代码运行

代码下载:https://github.com/a123demi/spring-boot-integration

 

代码主要讲解

主要依赖

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

 

 

数据库连接

spring.application.name=spirngboot-int-mongodbeg

spring.data.mongodb.database=admin
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.password=root
spring.data.mongodb.port=27017
spring.data.mongodb.username=root

 

 

通过MongoTemplate来调用各种增删改查的语句,比如

        Query query=new Query(Criteria.where("userName").is(userName));
        UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);

 

 

涉及的主要关键函数有

增
mongoTemplate.save(user);
删
mongoTemplate.remove(query,UserEntity.class);
改
Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
//更新查询返回结果集的第一条
WriteResult result =mongoTemplate.updateFirst(query,update,UserEntity.class);
查
Query query=new Query(Criteria.where("userName").is(userName));
UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);

 

 高级查询

分页查询

 //利用工具类拼装分页信息 
 SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable(); 
 MongoDBPageModel pm=new MongoDBPageModel(); 
 pm.setPagesize(3);
 pm.setPagenumber(1); 
 List<Order> orders = new ArrayList<>();
 //排序信息
 orders.add(new Order(Direction.DESC, "age"));
 Sort sort = new Sort(orders);
 pm.setSort(sort);
 pageable.setPage(pm);
 //拼装查询信息
 Query query = new Query();
 Criteria criteria = new Criteria();
 query.addCriteria(criteria.where("age").gte(6).lte(18));
 //检索6-18岁的
 query.addCriteria(criteria.where("name").regex("文"));
 //模糊查询名字
 Long count = mongoTemplate.count(query, OrdersData.class);
 //查询总记录数
 List<Entry> list = mongoTemplate.find(query.with(pageable), Entry.class);
//分页聚合查询(多表多条件关联分页查询)
 //mongodb中有两个表,一个是人物表 一个是宠物表,一个人可以有多个宠物
 //人物表字段为 String id, Integer age,String remark;
 //宠物表字段为 String id, String manId,String age,String remark;
 //拼装分页信息
 SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
 MongoDBPageModel pm=new MongoDBPageModel();
 pm.setPagesize(2);
 pm.setPagenumber(1);
 List<Order> orders = new ArrayList<>();
 //排序
 orders.add(new Order(Direction.DESC, "age"));
 Sort sort = new Sort(orders);
 pm.setSort(sort);
 pageable.setPage(pm);
 //拼装关联信息
 LookupOperation lookupOperation = LookupOperation.newLookup(). from("dogData"). //关联表名
 localField("_id"). //关联字段
 foreignField("manId").//主表关联字段对应的次表字段
 as("dogs");//查询结果集合名
 //拼装具体查询信息
 //次表
 Criteria ordercri = Criteria.where("dogs").not().size(0);//只查询有宠物的人
 ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
 AggregationOperation match = Aggregation.match(ordercri);
 //主表
 Criteria qqq=Criteria.where("name").regex("文");//只查询名字中带有文的人
 AggregationOperation match1= Aggregation.match(qqq);
 //分页查询
 Aggregation aggregation = Aggregation.newAggregation(match1,lookupOperation,match,Aggregation.sort(pageable.getSort()),//排序 Aggregation.skip(pageable.getPageNumber()>1?(pageable.getPageNumber()-1)*pageable.getPageSize():0),//pagenumber
 Aggregation.limit(pageable.getPageSize()));//pagesize
 //总数查询
 Aggregation counts = Aggregation.newAggregation(match1,lookupOperation,match).; int count = mongoTemplate.aggregate(counts, "manEntry", BasicDBObject.class).getMappedResults().size(); List<BasicDBObject> results = mongoTemplate.aggregate(aggregation, "manEntry", BasicDBObject.class).getMappedResults(); //查询出的结果集为BasicDBObject类型
 //解析过程
 for (BasicDBObject b :results ) { 
 //转化为jsonobject对象
 JSONObject jsonObject = new JSONObject(b);
 String id = jsonObject.get("id").toString();
 Integer age = ((int) jsonObject.get("age")); 
 String remark = jsonObject.get("remark").toString(); 
 //转化为jsonarray 
 JSONArray dogs = jsonObject.getJSONArray("dogs");
 if (dogs.size() > 0) {
 for (int i = 0; i < dogs.size(); i++) { 
 JSONObject job = dogs.getJSONObject(i);
 String dogId = job.get("id").toString(); 
 String manId = job.get("manId").toString();
 } 
 } 
 } 
 } 

 可参考网址:https://blog.csdn.net/weixin_39804646/article/details/82155898#commentBox

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!