springboot+mongodb的基本操作 CRUD

1、基于MongoRepository操作 mongodb

配置mongodb上一个文件有提现,这里就不写了。

Docker创建一个mongodb实例,并用springboot连接 mongodb进行读写文件-CSDN博客

java 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
</dependencies>
java 复制代码
@Data
@Document(collection = "User")
public class User {
    @Id
    private String id;
    private String name;
    private Integer age;
    private String email;
    private String createDate;
}
java 复制代码
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
java 复制代码
@ActiveProfiles("test")
@SpringBootTest
public class MongoRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void createTest() {
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        user.setEmail("123@qq.com");

        User user1 = userRepository.save(user);
        System.out.println(user1);
    }

    @Test
    public void findAllTest() {
        List<User> list = userRepository.findAll();
        System.out.println(list);
    }

    @Test
    public void findByIdTest() {
        Optional<User> optional = userRepository.findById("6195b9a5c6e3b8f8a0e8c6e3");
        optional.ifPresent(System.out::println);
    }

    @Test
    public void findConditionTest() {
        //name="张三" and age = 20
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        Example<User> example = Example.of(user);

        userRepository.findAll(example);
    }

    @Test
    public void findLikeTest() {
        //设置模糊查询规则
        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        User user = new User();
        user.setAge(20);
        user.setName("m");
        Example<User> example = Example.of(user,matcher);

        userRepository.findAll(example);
    }

    @Test
    public void findPageTest(){
        int pageNo = 1;
        int pageSize = 2;
        Pageable pageable = PageRequest.of(pageNo, pageSize);

        User user = new User();
        user.setAge(20);
        user.setName("张三");
        Example<User> example = Example.of(user);

        Page<User> page = userRepository.findAll(example, pageable);
        System.out.println(page.getTotalElements());
    }

    @Test
    public void updateTest(){
        User user = userRepository.findById("6195b9a5c6e3b8f8a0e8c6e3").get();
        user.setName("李四");
        User user1 = userRepository.save(user);
        System.out.println(user1);
    }

    @Test
    public void removeTest(){
        userRepository.deleteById("6195b9a5c6e3b8f8a0e8c6e3");
    }

}

2、基于MongoTemplate操作mongodb

java 复制代码
import com.bilibili.domain.User;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
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.ActiveProfiles;

import java.util.List;
import java.util.regex.Pattern;


@SpringBootTest
@ActiveProfiles("test")
public class MongoTemplateTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final String ID = "675bdbb2d3031003cab59e2f";

    @Test
    public void createTest() {
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        user.setEmail("123@qq.com");

        User user1 = mongoTemplate.insert(user);
        System.out.println(user1);
    }

    @Test
    public void findAllTest() {
        List<User> list = mongoTemplate.findAll(User.class);
        System.out.println(list);
    }

    @Test
    public void findByIdTest() {
        User user = mongoTemplate.findById(ID, User.class);
        System.out.println(user);
    }

    @Test
    public void findConditionTest() {
        Query query = new Query(Criteria.where("name").is("张三").and("age").is(20));
        List<User> userList = mongoTemplate.find(query, User.class);
        System.out.println(userList);
    }

    @Test
    public void findLikeTest() {
        String name = "张三";
        String regex = String.format("%s%s%s","^.*",name,".*$");
        // 模糊查询
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        Query query = new Query(Criteria.where("name").regex(pattern));
        List<User> userList = mongoTemplate.find(query, User.class);
        System.out.println(userList);
    }

    @Test
    public void findPageTest(){
        int pageNo = 1;
        int pageSize = 2;

        Query query = new Query();
        //查询记录数
        long count = mongoTemplate.count(query, User.class);
        //分页查询 (pageNo - 1) * pageSize 表示开始位置
        List<User> list = mongoTemplate.find(query.skip((pageNo - 1) * pageSize).limit(pageSize), User.class);
        System.out.println(count);
        System.out.println(list);
    }

    @Test
    public void updateTest(){
        //更新所有符合条件的数据
        User user = mongoTemplate.findById(ID, User.class);
        user.setName("李四");
        user.setAge(30);

        //过滤条件
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        //更新内容
        Update update = new Update();
        update.set("name",user.getName());
        update.set("age",user.getAge());

        UpdateResult upsert = mongoTemplate.upsert(query, update, User.class);
        //更新条数
        long modifiedCount = upsert.getModifiedCount();
        System.out.println(modifiedCount);
    }

    @Test
    public void removeTest(){
        Query query = new Query(Criteria.where("_id").is(ID));
        DeleteResult remove = mongoTemplate.remove(query, User.class);
        //删除条数
        long deletedCount = remove.getDeletedCount();
        System.out.println(deletedCount);
    }
}
相关推荐
Ai 编码助手12 分钟前
Go语言如何实现限制用户 1 分钟内最多请求 1000 次?
开发语言·后端·golang
zzyh12345624 分钟前
搭建springcloud脚手架
后端·spring·spring cloud
我要学编程(ಥ_ಥ)25 分钟前
初始JavaEE篇 —— 快速上手 SpringBoot
java·spring boot·spring·java-ee
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS夕阳红公寓管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
Edward-tan1 小时前
【玩转全栈】----Django模板的继承
后端·python·django
汪子熙1 小时前
深入解析 npm ci 的运行原理及其在 Angular 项目中的应用
javascript·后端
SomeB1oody1 小时前
【Rust自学】13.8. 迭代器 Pt.4:创建自定义迭代器
开发语言·后端·rust
步、步、为营1 小时前
ASP.NET Core全球化与本地化:打造多语言应用
后端·microsoft·asp.net
半夏知半秋1 小时前
rust学习-函数的定义与使用
服务器·开发语言·后端·学习·rust
Q_27437851091 小时前
django应急物资管理系统
后端·python·django