maven repository
https://mvnrepository.com/search?q=spring-boot-starter-data-mongodb
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
<version>2.5.4version>
dependency>
spring:
data:
mongodb:
database: stu
uri: mongodb://localhost:27017/stu
此处我用的是本地安装的mongodb,所以没有用户名和密码,有用户名和密码的格式是
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test,其中name是用户名,pass是密码
如果要配置多个数据库,则中间用","分割,例如
spring.data.mongodb.uri=mongodb://192.168.1.1:20000,192.168.1.2:20000,192.168.252.12:20000/test
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@NoArgsConstructor
@Data
@AllArgsConstructor
//这个是指这个实体类和mongo的mongoTest绑定
@Document(collection="mongoTest")
public class Student {
@Id
private String id;
private String name;
private String sex;
private Integer age;
private Integer score;
public Student(String name, String sex, Integer age, Integer score) {
this.name = name;
this.sex = sex;
this.age = age;
this.score = score;
}
}
自己定一个实体类的仓库继承这个类,就可用里面集成的方法啦 类似MybatisPlus巨好用!
import org.springframework.data.mongodb.repository.MongoRepository;
public interface StudentReposity extends MongoRepository<Student, String> {
}
//批量增加
@Test
public void testAdd() {
Student student1 = new Student("小红", "男", 18, 57);
Student student2 = new Student("小啊", "男", 21, 67);
Student student3 = new Student("小是", "男", 35, 79);
Student student4 = new Student("小的", "男", 14, 96);
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student3);
list.add(student2);
list.add(student4);
studentReposity.saveAll(list);
}
@Test
public void testCount() {
//因为StudentReposity 与 Student绑定 ,Student与mongo表mongoTest绑定
//因此count的是表mongoTest的记录条数
long count = studentReposity.count();
System.out.println(count);
}
//获取全部数据
@Test
public void testFindAll() {
List<Student> all = studentReposity.findAll();
System.out.println(all.toString());
}
//根据id查询单条记录
Student student = new Student();
student.setId("6153bd172aabe434a11ea918");
Optional<Student> one = studentReposity.findOne(Example.of(student));
Optional<Student> byId = studentReposity.findById("6153bd172aabe434a11ea918");
System.out.println("单条记录根据对象查询:"+one);
System.out.println("单条记录根据id查询:"+byId);
//查询结果排序 前面排序条件后面排序字段
Sort sort = Sort.by(Sort.Direction.DESC,"sex","score","age");
List<Student> all = studentReposity.findAll(sort);
System.out.println("排序后结果集:");
all.forEach(System.out::println);
//根据sex筛选再排序
Student student1 = new Student();
student1.setSex("女");
List<Student> screenBySexList = studentReposity.findAll(Example.of(student1), sort);
System.out.println("筛选后结果集:");
screenBySexList.forEach(System.out::println);
//删除数据
@Test
public void testDel(){
boolean b = studentReposity.existsById("6153bd172aabe434a11ea918");
System.out.println(b);
studentReposity.deleteById("6153bd172aabe434a11ea918");
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @Description: SpringData 集成mongo Demo
* @Author: liyuang
* @Date: 2021/9/29 9:50
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTestDemo {
@Resource
StudentReposity studentReposity;
//批量增加
@Test
public void testAdd() {
Student student1 = new Student("小红", "男", 18, 57);
Student student2 = new Student("小啊", "男", 21, 67);
Student student3 = new Student("小是", "男", 35, 79);
Student student4 = new Student("小的", "男", 14, 96);
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student3);
list.add(student2);
list.add(student4);
studentReposity.saveAll(list);
}
@Test
public void testCount() {
//因为StudentReposity 与 Student绑定 ,Student与mongo表mongoTest绑定
//因此count的是表mongoTest的记录条数
long count = studentReposity.count();
System.out.println(count);
}
//获取全部数据
@Test
public void testFindAll() {
List<Student> all = studentReposity.findAll();
System.out.println(all.toString());
}
//查询数据
@Test
public void testFindOne(){
//根据id查询单条记录
Student student = new Student();
student.setId("6153bd172aabe434a11ea918");
Optional<Student> one = studentReposity.findOne(Example.of(student));
Optional<Student> byId = studentReposity.findById("6153bd172aabe434a11ea918");
System.out.println("单条记录根据对象查询:"+one);
System.out.println("单条记录根据id查询:"+byId);
//查询结果排序 前面排序条件后面排序字段
Sort sort = Sort.by(Sort.Direction.DESC,"sex","score","age");
List<Student> all = studentReposity.findAll(sort);
System.out.println("排序后结果集:");
all.forEach(System.out::println);
//根据sex筛选再排序
Student student1 = new Student();
student1.setSex("女");
List<Student> screenBySexList = studentReposity.findAll(Example.of(student1), sort);
System.out.println("筛选后结果集:");
screenBySexList.forEach(System.out::println);
}
//删除数据
@Test
public void testDel(){
boolean b = studentReposity.existsById("6153bd172aabe434a11ea918");
System.out.println(b);
studentReposity.deleteById("6153bd172aabe434a11ea918");
}
}
插入重复数据
批操作
//增加数据
@Test
public void testAdd() {
Student student = new Student("小红", "男", 18, 57);
Student student2 = new Student("小啊", "男", 21, 67);
Student student3 = new Student("小是", "男", 35, 79);
Student student4 = new Student("小的", "男", 14, 96);
List<Student> list = new ArrayList<>();
list.add(student);
list.add(student3);
list.add(student2);
list.add(student4);
// 保存对象到mongodb
mongoTemplate.save(student);
student.setId(UUID.randomUUID().toString().replace("-", ""));
mongoTemplate.insert(student);
// 根据集合名称保存对象到mongodb
mongoTemplate.save(student, "mongodb_student1");
mongoTemplate.insert(student, "mongodb_student2");
// 根据集合名称保存list到mongodb
mongoTemplate.insert(list, "mongodb_student4");
}
// 更新一条数据
mongoTemplate.updateFirst(query, update, Student.class);
mongoTemplate.updateFirst(query, update, "mongodb_student");
mongoTemplate.updateFirst(query, update, Student.class, "mongodb_student4");
// 更新多条数据
query = Query.query(Criteria.where("name").is("小红"));
mongoTemplate.updateMulti(query, update, Student.class);
mongoTemplate.updateMulti(query, update, "mongodb_student");
mongoTemplate.updateMulti(query, update, Student.class, "mongodb_student4");
// 更新数据,如果数据不存在就新增
query = Query.query(Criteria.where("_id").is("123123123"));
mongoTemplate.upsert(query, update, Student.class);
mongoTemplate.upsert(query, update, "mongodb_student");
mongoTemplate.upsert(query, update, Student.class, "mongodb_student4");
// 查询name=admin id = 6153fdfef6f4e069f61dc05b
Query query = Query.query(
Criteria.where("name").is("admin")
.and("id").is("6153fdfef6f4e069f61dc05b")
);
List<Student> students = mongoTemplate.find(query, Student.class);
System.out.println("不指定集合筛选查询:");
//不指定 会找到和Student 绑定的集合查询
students.forEach(System.out::println);
Query condition = Query.query(
Criteria.where("name").is("小红")
);
List<Student> mongodb_student = mongoTemplate.find(condition, Student.class, "mongodb_student4");
System.out.println("指定集合筛选查询:");
mongodb_student.forEach(System.out::println);
// 查询多个
Query query3 = Query.query(
Criteria.where("id").in("6153fdfef6f4e069f61dc05b", "6153fea51be2b9334edc620c", "7f48f39fc5b346018d25c3c907d567da"))
.with(Sort.by(Sort.Order.desc("score"))
);
List<Student> list = this.mongoTemplate.find(query3, Student.class);
System.out.println("查询多个并根据分数排序:");
list.forEach(System.out::println);
// 查询数量
Criteria criteria = Criteria.where("name").is("admin")
.and("sex").is("男");
Query query4 = Query.query(criteria);
long count = this.mongoTemplate.count(query4, Student.class);
System.out.println("名字为admin的男生有:");
System.out.println(count);
// 查询所有
List<Student> all = mongoTemplate.findAll(Student.class);
System.out.println("所有-不指定集合:");
all.forEach(System.out::println);
List<Student> mongodbStudent = mongoTemplate.findAll(Student.class, "mongodb_student1");
System.out.println("所有-指定集合:");
mongodbStudent.forEach(System.out::println);
// 分页查询 page页码,pageSize每页展示几个
Integer page = 1;
Integer pageSize = 3;
Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
Query query2 = new Query().with(pageable);
List<Student> studentList = this.mongoTemplate.find(query2, Student.class, "mongodb_student4");
System.out.println("分页 每页3个 查询:");
studentList.forEach(System.out::println);
List<Student> list = new ArrayList<>();
Student student = new Student();
student.setId("6153fdfef6f4e069f61dc05b");
list.add(student);
Query query = Query.query(Criteria.where("id").in("a7ec0396b6f1475ca6bf44daf25e8032", "123123123"));
// 根据条件删除
mongoTemplate.remove(query, student.getClass());
// 根据条件删除(可删除多条)
mongoTemplate.remove(query, Student.class, "mongodb_student4");
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @Description: SpringBoot 集成mongo Demo
* @Author: liyuang
* @Date: 2021/9/29 13:50
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTestDemoBySpringBoot {
@Resource
MongoTemplate mongoTemplate;
//增加数据
@Test
public void testAdd() {
// 插入重复数据
// insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,不保存当前数据。
// save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
// 批操作
// insert: 可以一次性插入一整个列表,而不用进行遍历操作,效率相对较高。
// save: 需要遍历列表,进行一个个的插入。
Student student = new Student("小红", "男", 18, 57);
Student student2 = new Student("小啊", "男", 21, 67);
Student student3 = new Student("小是", "男", 35, 79);
Student student4 = new Student("小的", "男", 14, 96);
List<Student> list = new ArrayList<>();
list.add(student);
list.add(student3);
list.add(student2);
list.add(student4);
// 保存对象到mongodb
mongoTemplate.save(student);
student.setId(UUID.randomUUID().toString().replace("-", ""));
mongoTemplate.insert(student);
// 根据集合名称保存对象到mongodb
mongoTemplate.save(student, "mongodb_student1");
mongoTemplate.insert(student, "mongodb_student2");
// 根据集合名称保存list到mongodb
mongoTemplate.insert(list, "mongodb_student4");
}
//查询数据
@Test
public void testFind() {
// 查询name=admin id = 6153fdfef6f4e069f61dc05b
Query query = Query.query(
Criteria.where("name").is("admin")
.and("id").is("6153fdfef6f4e069f61dc05b")
);
List<Student> students = mongoTemplate.find(query, Student.class);
System.out.println("不指定集合筛选查询:");
//不指定 会找到和Student 绑定的集合查询
students.forEach(System.out::println);
Query condition = Query.query(
Criteria.where("name").is("小红")
);
List<Student> mongodb_student = mongoTemplate.find(condition, Student.class, "mongodb_student4");
System.out.println("指定集合筛选查询:");
mongodb_student.forEach(System.out::println);
// 查询所有
List<Student> all = mongoTemplate.findAll(Student.class);
System.out.println("所有-不指定集合:");
all.forEach(System.out::println);
List<Student> mongodbStudent = mongoTemplate.findAll(Student.class, "mongodb_student1");
System.out.println("所有-指定集合:");
mongodbStudent.forEach(System.out::println);
// 分页查询 page页码,pageSize每页展示几个
Integer page = 1;
Integer pageSize = 3;
Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
Query query2 = new Query().with(pageable);
List<Student> studentList = this.mongoTemplate.find(query2, Student.class, "mongodb_student4");
System.out.println("分页 每页3个 查询:");
studentList.forEach(System.out::println);
// 查询多个
Query query3 = Query.query(
Criteria.where("id").in("6153fdfef6f4e069f61dc05b", "6153fea51be2b9334edc620c", "7f48f39fc5b346018d25c3c907d567da"))
.with(Sort.by(Sort.Order.desc("score"))
);
List<Student> list = this.mongoTemplate.find(query3, Student.class);
System.out.println("查询多个并根据分数排序:");
list.forEach(System.out::println);
// 查询数量
Criteria criteria = Criteria.where("name").is("admin")
.and("sex").is("男");
Query query4 = Query.query(criteria);
long count = this.mongoTemplate.count(query4, Student.class);
System.out.println("名字为admin的男生有:");
System.out.println(count);
}
//更新数据
@Test
public void testUpdate() {
Query query = Query.query(Criteria.where("_id").is("6153fdfef6f4e069f61dc05b"));
Update update = Update.update("name", "ttttttttt");
// 更新一条数据
mongoTemplate.updateFirst(query, update, Student.class);
mongoTemplate.updateFirst(query, update, "mongodb_student");
mongoTemplate.updateFirst(query, update, Student.class, "mongodb_student4");
// 更新多条数据
query = Query.query(Criteria.where("name").is("小红"));
mongoTemplate.updateMulti(query, update, Student.class);
mongoTemplate.updateMulti(query, update, "mongodb_student");
mongoTemplate.updateMulti(query, update, Student.class, "mongodb_student4");
// 更新数据,如果数据不存在就新增
query = Query.query(Criteria.where("_id").is("123123123"));
mongoTemplate.upsert(query, update, Student.class);
mongoTemplate.upsert(query, update, "mongodb_student");
mongoTemplate.upsert(query, update, Student.class, "mongodb_student4");
}
//删除数据
@Test
public void testDel() {
List<Student> list = new ArrayList<>();
Student student = new Student();
student.setId("6153fdfef6f4e069f61dc05b");
list.add(student);
Query query = Query.query(Criteria.where("id").in("a7ec0396b6f1475ca6bf44daf25e8032", "123123123"));
// 根据条件删除
mongoTemplate.remove(query, student.getClass());
// 根据条件删除(可删除多条)
mongoTemplate.remove(query, Student.class, "mongodb_student4");
}
}