添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置文件
#端口
server.port=8888
##mongo主机地址
spring.data.mongodb.host=127.0.0.1
##端口号
spring.data.mongodb.port=27017
#数据库名称
spring.data.mongodb.database=test
创建两个实体类测试
@Data
@Document(collection = "student")
public class Student {
private String id;
private String name;
private String unicode;
}
@Data
@Document(collection = "teacher")
public class Teacher {
private String id;
private String name;
private String project;
private List<Student> students;
}
为了方便test类中测试
@SpringBootTest
class MongodbApplicationTests {
@Resource
private MongoTemplate mongoTemplate;
@Resource
private MongoUtil mongoUtil;
@Test
void addStudent() {
int a = 1;
while (a <= 100) {
Student student = new Student();
student.setName("name" + a);
student.setUnicode(UUID.randomUUID().toString());
Student insert = mongoTemplate.insert(student);
System.out.println(insert);
a++;
}
}
@Test
void findByName() {
Query query = new Query(Criteria.where("name").is("name1"));
List<Student> students = mongoTemplate.find(query, Student.class);
System.out.println(students);
}
@Test
void findByNameAndUnicode() {
// Query query = new Query(Criteria.where("name").is("name1").and("unicode").is("e24928f8-ef7a-479d-8211-fb4e01c344f5"));
Student student = new Student();
student.setName("name1");
student.setUnicode("e24928f8-ef7a-479d-8211-fb4e01c344f5");
Query query = new Query(Criteria.byExample(student));
List<Student> students = mongoTemplate.find(query, Student.class);
System.out.println(students);
}
@Test
void addTeacher() {
List<String> str = new ArrayList<>();
str.add("name1");
str.add("name2");
Query query = new Query(Criteria.where("name").in(str));
List<Student> students = mongoTemplate.find(query, Student.class);
int a = 1;
while (a < 100) {
Teacher teacher = new Teacher();
teacher.setName("teacher");
teacher.setProject("project" + a);
teacher.setStudents(students);
Teacher insert = mongoTemplate.insert(teacher);
a++;
}
}
/**
* 查询list中对象的值
*/
@Test
void findTeacher() {
Query query = new Query(Criteria.where("students.name").is("name1").and("project").is("project1"));
List<Teacher> teachers = mongoTemplate.find(query, Teacher.class);
System.out.println(teachers);
}
/**
* 分页查询
*/
@Test
void findByPage() {
// Query query = new Query(Criteria.where("students.name").is("name1").and("project").is("project1"));
Query query = new Query(new Criteria());
// query.with(Sort.by(Sort.Direction.DESC, "time"));
mongoUtil.start(2, 2, query);
List<Teacher> teachers = mongoTemplate.find(query, Teacher.class);
long count = mongoTemplate.count(query, Teacher.class);
PageHelper pageHelper = mongoUtil.pageHelper(count, teachers);
System.out.println(pageHelper);
}
/**
* 更新操作
*/
@Test
void update() {
Query query = new Query();
query.addCriteria(Criteria.where("project").is("project2"));
Update update = new Update();
// //直接更新
// update.set("students", "更新成功");
// //文档不存在的话会插入一条新的记录
// update.setOnInsert("students", "更新成功1");
// //移除这个键
// update.unset("students");
//加入到一个集合中,不会重复
// update.addToSet("students", "更新成功3");
//需要传值,会清空其他属性
// update.addToSet("students");
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Teacher.class);
System.out.println(updateResult);
}
}
自己封装工具类用于分页
/**
* @author shawn
*/
@Data
public class PageHelper<T> {
private long currentPage;
private long total;
private long pageSize;
private List<T> list;
public PageHelper(long pageNum, long total, long pageSize, List<T> list) {
this.currentPage = pageNum;
this.total = total;
this.pageSize = pageSize;
this.list = list;
}
public PageHelper(long pageNum, long pageSize, List<T> list) {
this.currentPage = pageNum;
this.pageSize = pageSize;
this.list = list;
}
}
工具类
package com.example.mongodb.util;
import lombok.Data;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.regex.Pattern;
/**
* @author shawn
*/
@Data
@Component
public class MongoUtil<T> {
public Integer pageSize;
private Integer currentPage;
public void start(Integer currentPage, Integer pageSize, Query query) {
pageSize = pageSize == 0 ? 10 : pageSize;
query.limit(pageSize);
query.skip((currentPage - 1) * pageSize);
this.pageSize = pageSize;
this.currentPage = currentPage;
}
public PageHelper pageHelper(long total, List<T> list) {
return new PageHelper(this.currentPage, total, this.pageSize, list);
}
public PageHelper pageHelper(List<T> list) {
return new PageHelper(this.currentPage, this.pageSize, list);
}
public PageHelper pageHelper(long currentPage, long total, long pageSize, List<T> list) {
return new PageHelper(currentPage, total, pageSize, list);
}
public PageHelper pageHelper(long currentPage, long pageSize, List<T> list) {
return new PageHelper(currentPage, pageSize, list);
}
/**
* 用于模糊查询忽略大小写
*
* @param string
* @return
*/
public Pattern getPattern(String string) {
Pattern pattern = Pattern.compile("^.*" + string + ".*$", Pattern.CASE_INSENSITIVE);
return pattern;
}
}
批量插入
需要用到BulkOperations,参考官方文档
https://docs.mongodb.com/manual/core/bulk-write-operations/
批量插入示例如下:
List<Object> insertDataList;
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
operations.insert(insertDataList);
BulkWriteResult result = operations.execute();
批量修改示例如下:
List<Object> updateDataList;
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
updateDateList.forEach(date -> {
Query queryUpdate = new Query();
queryUpdate.addCriteria(where("_id").is(value));
Update update = new Update();
update.set(field1, value1).set(field2, value2);
operations.updateOne(queryUpdate, update);
});
BulkWriteResult result = operations.execute();
利用BulkOperations的upsert方法可以同时支持插入和更新操作,示例如下:
List<T> dataList = new ArrayList<>();
List<Pair<Query, Update>> updateList = new ArrayList<>(dataList.size());
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
dataList.forEach(data -> {
Query query = new Query(new
Criteria(field1).is(value1)).addCriteria(new Criteria(field2).is(value2));
Update update = new Update();
for (int index = 0; index < dataList.size(); index++) {
String key = data.getKey();
String value = data.getValue();
update.set(key, value);
}
Pair<Query, Update> updatePair = Pair.of(query, update);
updateList.add(updatePair);
});
operations.upsert(updateList);
BulkWriteResult result = operations.execute();
备注:BulkOperations.BulkMode.UNORDERED 和 BulkOperations.BulkMode.ORDERED的区别:
UNORDERED是平行处理,即使某条记录出错了,其余的也会继续处理;
ORDERED是队列排序处理,只要中途有个失败了,那么后续的操作流程就会终止了。
enum BulkMode {
/** Perform bulk operations in sequence. The first error will cancel processing. */
ORDERED,
/** Perform bulk operations in parallel. Processing will continue on errors. */
UNORDERED
};
网友评论