相关推荐recommended
SpringBoot——整合MongoDB详解
作者:mmseoamin日期:2023-12-18

引入依赖


   org.springframework.boot
   spring-boot-starter-data-mongodb

配置文件

spring:
  data:
    mongodb:
      host: 127.0.0.1
      database: test
      port: 27017
      # 也可以使用uri   mongodb://127.0.0.1:27017/test

创建实体类

public class Student implements Serializable{
    
    @Id
    private String studentId;
    
    private String studentName;
    
    private Integer studentAge;
    
    private Double studentScore;
    
    private Date studentBirthday;
    public Student(String studentId, String studentName, Integer studentAge, Double studentScore, Date studentBirthday) {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentAge = studentAge;
        this.studentScore = studentScore;
        this.studentBirthday = studentBirthday;
    }
    public Student() {
    }
    public String getStudentId() {
        return studentId;
    }
    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public Integer getStudentAge() {
        return studentAge;
    }
    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
    public Double getStudentScore() {
        return studentScore;
    }
    public void setStudentScore(Double studentScore) {
        this.studentScore = studentScore;
    }
    public Date getStudentBirthday() {
        return studentBirthday;
    }
    public void setStudentBirthday(Date studentBirthday) {
        this.studentBirthday = studentBirthday;
    }
    @Override
    public String toString() {
        return "Student{" +
                "studentId='" + studentId + '\'' +
                ", studentName='" + studentName + '\'' +
                ", studentAge=" + studentAge +
                ", studentScore=" + studentScore +
                ", studentBirthday=" + studentBirthday +
                '}';
    }
}

dao层

1、JPA方式
/**
 * @Author: acton_zhang
 * @Date: 2023/5/9 12:41 上午
 * @Version 1.0
 * JPA方式
 * 继承MongoRepository即可,不需要实现类
 */
public interface StudentRepository extends MongoRepository {
}

测试:

import data.dao.StudentRepository;
import data.domain.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import java.util.*;
/**
 * @Author: acton_zhang
 * @Date: 2023/5/9 12:44 上午
 * @Version 1.0
 */
@SpringBootTest
public class StudentRepositoryTest {
    @Autowired
    private StudentRepository studentRepository;
    /**
     * 插入单条数据
     */
    @Test
    public void insertOne() {
        Student student = new Student("009", "tom", 18, 88.2d, new Date());
        studentRepository.insert(student);
    }
    /**
     * 插入多条数据
     */
    @Test
    public void insertMany() {
        Student student1 = new Student("002", "jerry", 19, 38.2d, new Date());
        Student student2 = new Student("003", "mike", 20, 78.2d, new Date());
        List list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        studentRepository.insert(list);
    }
    /**
     * 修改数据
     */
    @Test
    public void update() {
        Optional op = studentRepository.findById("001");
        Student student = op.get();
        student.setStudentAge(222);
        studentRepository.save(student);
    }
    /**
     * 查询数据
     */
    @Test
    public void query() {
        //根据Id查询单个对象
        Optional stuOp = studentRepository.findById("001");
        System.out.println(stuOp.get());
        //根据字段查询单个对象
        Student student = new Student();
        student.setStudentAge(19);
        Optional stuOp1 = studentRepository.findOne(Example.of(student));
        System.out.println(stuOp1.get());
        //根据id列表查询多个对象
        Iterable itStu = studentRepository.findAllById(Arrays.asList(new String[]{"001", "002"}));
        Iterator itor = itStu.iterator();
        while (itor.hasNext())
            System.out.println(itor.next());
        //查询所有
        List all = studentRepository.findAll();
        //查询所有并排序
        List all1 = studentRepository.findAll(Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName")));
        for (Student stu : all1)
            System.out.println(stu);
        //根据条件查询所有并排序
        Student student1 = new Student();
        student1.setStudentName("tom");
        List all2 = studentRepository.findAll(Example.of(student1), Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName")));
        for (Student stu : all2)
            System.out.println(stu);
        //根据条件查询所有并排序,且分页
        Pageable pageable = PageRequest.of(0, 2);
        Page all3 = studentRepository.findAll(pageable);
        List content = all3.getContent();
        for (Student stu : content)
            System.out.println(stu);
    }
    /**
     * 其他操作
     */
    @Test
    public void other() {
        //count
        long count = studentRepository.count();
        System.out.println(count);
        Student student = new Student();
        student.setStudentAge(18);
        long count1 = studentRepository.count(Example.of(student));
        System.out.println(count1);
        //exists
        boolean exists = studentRepository.exists(Example.of(student));
        System.out.println(exists);
        boolean b = studentRepository.existsById("001");
        System.out.println(b);
    }
    /**
     * 删除操作
     */
    @Test
    public void remove() {
        //根据id删除单个对象
        studentRepository.deleteById("001");
        //根据字段删除
        Student student = new Student();
        student.setStudentAge(20);
        studentRepository.delete(student);
        //删除所有
        studentRepository.deleteAll();
        //根据字段删除多个
        Student student1 = new Student();
        student1.setStudentName("jerry");
        List list = new ArrayList<>();
        list.add(student);
        list.add(student1);
        studentRepository.deleteAll(list);
    }
}
2、MongoTemplate方式

dao接口:

public interface StudentDao {
    //插入单个对象
    void addOne(Student student);
    //根据id删除单个对象
    void deleteOneById(String  studentId);
    //修改单个对象
    void updateOne(Student student);
    //根据id获取单个对象
    Student findOneById(String studentId);
    
    //获取全部学生
    List findAll();
}

实现类:

public class StudentDaoImpl implements StudentDao {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void addOne(Student student) {
        mongoTemplate.save(student);
    }
    @Override
    public void deleteOneById(String studentId) {
        Student stu = mongoTemplate.findById(studentId, Student.class);
        if (stu != null)
            mongoTemplate.remove(stu);
    }
    @Override
    public void updateOne(Student student) {
        mongoTemplate.save(student);
    }
    @Override
    public Student findOneById(String studentId) {
        return mongoTemplate.findById(studentId, Student.class);
    }
    @Override
    public List findAll() {
        return mongoTemplate.findAll(Student.class);
    }
}

测试类:

@SpringBootTest
public class StudentDaoTest {
    @Autowired
    private StudentDao studentDao;
    @Test
    void addOneStudent(){
//        插入10行
        for (Integer count = 0; count < 10; count++) {
            Student student = new Student();
            student.setStudentId("study_"+count);
            student.setStudentName("Echo"+count);
            student.setStudentAge(count);
            student.setStudentScore(98.5-count);
            student.setStudentBirthday(new Date());
            studentDao.addOne(student);
        }
    }
    @Test
    void deleteOneStudentByStudentId(){
//        删除id为study_0的学生
        studentDao.deleteOneById("study_0");
    }
    @Test
    void updateOneStudent(){
//        修改id为study_1的Student年龄为21
        Student student = studentDao.findOneById("study_1");
        student.setStudentAge(21);
        studentDao.updateOne(student);
    }
    @Test
    void getOneStudentByStudentId(){
        System.out.println(studentDao.findOneById("study_1"));
    }
    @Test
    void getAllStudent(){
        List studentList = studentDao.findAll();
        studentList.forEach(System.out::println);
    }
}

MongoTemplate

1、查询

is查询:

Query query = new Query();
// where...is... 相当于 where ? = ?
query.addCriteria(Criteria.where("数据库字段名").is("你的参数"));
// findOne 返回的是一个对象 Class代表你的表对应的映射类
mongoTemplate.findOne(query, Class.class);
// find 返回的是数组
mongoTemplate.find(query, Class.class);

in查询:

ArrayList list = new ArrayList<>();
// list代表你的数据
Query query = Query.query(Criteria.where("数据库字段").in(list));
mongoTemplate.find(query, Class.class);
// 如果想要查询指定的数据是否在数据库的数组中,可以用以下方法
Query query = Query.query(Criteria.where("数据库字段(数组)").is("你的数组"));

字符模糊查询:

Query query = Query.query(Criteria.where("name").regex("小"));

指定字段不返回:

query.fields().exclude("field");

数组中添加或删除一条数据:

Query query = Query.query(Criteria.where("_id").is("id"));
Update update = new Update();
// push方法可以在数组中添加一条数据
// pull方法可以在数组中删除一条数据
// update.pull()
update.push("字段名称", "data");
mongoTemplate.updateFirst(query, update, Class.class);

批量添加:

ArrayList list = new ArrayList<>();
mongoTemplate.insert(list, Class.class);

数组查询:

数组格式:
{
    name:"小明",
    age:13,
    friends:[
        {
            name:"小王",
            age:12
        },
        {
            name:"小李",
            age:18
        }
    ]
}
当要查询朋友中姓名为小王时
Query query = new Query();
query.addCriteria(Criteria.where("friends.$.name").is("小王"));
mongoTemplate.find(query, User.class);
同样更新时也是一样,但是注意,更新时查询条件需要添加
query.addCriteria(Criteria.where("friends").elemMatch(Criteria.where("name").is("小王"));
Update update = Update.update("friends.$.friends", "小赵");

数字字符串排序操作

对数据库中数字字符串排序:
加上这一行就行了 亲身体验
query.collation(Collation.of("zh").numericOrdering(true));
还有根据字符串排序时又是顺序并不是我们所想的字典序,加上下面这个也ok
query.collation(Collation.of("zh"));

分页:

//分页
query.limit(10);
//排序
Sort sort=Sort.by(Sort.Direction.DESC,"timestamp");
query.with(sort);

criteria:

关键字解释
eq等于,第一个参数是对象属性,第二个参数是值
allEq参数为一个Map对象,相当于多个eq的叠加
gt大于
ge大于等于
lt小于
le小于等于
between在两个值之间Expression.between(“age”,new Integer(10),new Integer(20));
likelike查询
inin查询
2、更新
User user = new User();
user.setId("5d1312aeb1829c279c6c256b");
user.setName("admin");
user.setAddress("测试");
Query query = Query.query(Criteria.where("_id").is("5d1312aeb1829c279c6c256b"));
Update update = Update.update("name","zs");
//  更新一条数据
mongoTemplate.updateFirst(query,update, User.class);
mongoTemplate.updateFirst(query,update, "mongodb_user");
mongoTemplate.updateFirst(query,update, User.class,"mongodb_user");
//  更新多条数据
mongoTemplate.updateMulti(query,update, User.class);
mongoTemplate.updateMulti(query,update,"mongodb_user");
mongoTemplate.updateMulti(query,update, User.class,"mongodb_user");
//  更新数据,如果数据不存在就新增
mongoTemplate.upsert(query,update, User.class);
mongoTemplate.upsert(query,update,"mongodb_user");
mongoTemplate.upsert(query,update, User.class,"mongodb_user");
3、插入
List list = new ArrayList<>();
User user= new User();//
user.setName("admin");
user.setAddress("测试");
list.add(user);
//  保存对象到mongodb
mongoTemplate.save(user);
mongoTemplate.insert(user);
//  根据集合名称保存对象到mongodb
mongoTemplate.save(user,"mongodb_user");
mongoTemplate.insert(user,"mongodb_user");
//  根据集合名称保存list到mongodb
mongoTemplate.save(list,"mongodb_user");
mongoTemplate.insert(list,"mongodb_user");
mongoTemplate.insert(list,User.class);
4、删除
List list = new ArrayList<>();
User user= new User();
user.setId("5d1312aeb1829c279c6c256b");
list.add(user);
Query query = Query.query(Criteria.where("_id").in("5d1312aeb1829c279c6c256b","5d13133ab1829c29d02ce29c"));
//  根据条件删除
mongoTemplate.remove(query);
mongoTemplate.remove(user);
mongoTemplate.remove(User.class);
//  根据条件删除(可删除多条)
mongoTemplate.remove(query,User.class,"mongodb_user");