废话不多说,最近的项目决定弃用mysql使用MongoDB,作为一个去年大学毕业的菜鸡在没有别人带的情况下从知道这么个数据库到熟练使用遇到不少坑,在网上找到的资料里也不是多么完善,磕磕绊绊总算初步学会使用MongoDB。谨在此哔哔一些自己的学习经验,希望能够帮助到一些初学者。
第一步、整合MongoDB。
这一步比较简单,引入依赖包。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>
第二步、springboot简单操作MongoDB——-增删改查
1.建立实体类。
/**
* @Date: 2018/8/28 21:22
* @Description:
*/
public class Entry {
private String id;
private String name;
private Integer age;
private String remark;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
2.切入正题——-增删改查
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @Date: 2018/8/28 21:30
* @Description:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class EntryTest {
/**
* 直接注入mongoTemplate即可使用
* */
private MongoTemplate mongoTemplate;
//增
@Test
public void add(Entry entry){
entry.setId("1");
entry.setName("张三");
entry.setAge(15);
entry.setRemark("喜欢打球、喜欢喝茶");
//存储操作
mongoTemplate.save(entry);
//指定集合名
mongoTemplate.save(entry,"人员表");
}
//删除
@Test
public void delete(String id){
mongoTemplate.remove("1");
mongoTemplate.remove("1","人员表");
Query query = new Query();
//拼装删除数据
query.addCriteria(Criteria.where("id").is("1"));
mongoTemplate.remove(query,"人员表");
mongoTemplate.remove(query,Entry.class);
}
//改
@Test
public void edit(Entry entry){
Query query = new Query(Criteria.where("id").is(entry.getId()));
//拼装修改数据
Update update = new Update();
update.set("name","李四");
update.set("remark","喜欢画画");
mongoTemplate.updateFirst(query, update, Entry.class);
}
//简单查
@Test
public void query(String id){
//单条
Query query = new Query(Criteria.where("id").is(id));//可累加条件
Entry entrY = mongoTemplate.findOne(query,Entry.class);
//多条
Query query2 = new Query(Criteria.where("remark").regex("喜欢"));//可累加条件
List entries = mongoTemplate.find(query, Entry.class);
}
}
3.分页查询——此处我写了两个工具类
import org.springframework.data.domain.Sort;
import java.io.Serializable;
/**
* @Auther:
* @Date: 2018/8/22 08:48
* @Description:
* @Version: 1.0
*/
public class MongoDBPageModel implements Serializable {
/**
* @Fields: serialVersionUID
* @Todo: TODO
*/
private static final long serialVersionUID = 1L;
// 当前页
private Integer pagenumber = 1;
// 当前页面条数
private Integer pagesize = 10;
// 排序条件
private Sort sort;
public Integer getPagenumber() {
return pagenumber;
}
public void setPagenumber(Integer pagenumber) {
this.pagenumber = pagenumber;
}
public Integer getPagesize() {
return pagesize;
}
public void setPagesize(Integer pagesize) {
this.pagesize = pagesize;
}
public Sort getSort() {
return sort;
}
public void setSort(Sort sort) {
this.sort = sort;
}
}
import java.io.Serializable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
* @Auther:
* @Date: 2018/8/22 10:19
* @Description:
* @Version: 1.0
*/
public class SpringbootMongoDBPageable implements Serializable,Pageable{
/**
* @Fields: serialVersionUID
* @Todo: TODO
*/
private static final long serialVersionUID = 1L;
MongoDBPageModel page;
public MongoDBPageModel getPage() {
return page;
}
public void setPage(MongoDBPageModel page) {
this.page = page;
}
@Override
public Pageable first() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getOffset() {
// TODO Auto-generated method stub
return (page.getPagenumber() - 1) * page.getPagesize();
}
@Override
public int getPageNumber() {
// TODO Auto-generated method stub
return page.getPagenumber();
}
@Override
public int getPageSize() {
// TODO Auto-generated method stub
return page.getPagesize();
}
@Override
public boolean hasPrevious() {
// TODO Auto-generated method stub
return false;
}
@Override
public Pageable next() {
// TODO Auto-generated method stub
return null;
}
@Override
public Pageable previousOrFirst() {
// TODO Auto-generated method stub
return null;
}
@Override
public Sort getSort() {
// TODO Auto-generated method stub
return page.getSort();
}
}
分页查询+分页聚合查询(多表多条件关联分页查询+结果集解析)——-依然测试类
/**
* @Date: 2018/8/28 21:30
* @Description:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class EntryTest {
/**
* 直接注入mongoTemplate即可使用
* */
private MongoTemplate mongoTemplate;
//分页查询
@Test
public void PageQuery(){
//利用工具类拼装分页信息
SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
MongoDBPageModel pm=new MongoDBPageModel();
pm.setPagesize(3);
pm.setPagenumber(1);
List 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 list = mongoTemplate.find(query.with(pageable), Entry.class);
}
//分页聚合查询(多表多条件关联分页查询)
@Test
public void PageQuery2(){
//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 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 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();
}
}
}
}
}
天晚了 来不及写的很详细了 明天还要工作,希望能帮助到大家~~~