SpringBoot整合MongoDB完成CRUD操作(超详细)

官方文档:https://www.mongodb.com/docs/manual/reference/connection-string/

01.导入依赖

  		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
            <version>2.2.6.RELEASEversion> 
        dependency> 

02.添加配置

# spring.data.mongodb.uri=mongodb://用户名:密码@IP:端口/数据库?authSource=admin
spring.data.mongodb.uri=mongodb://root:[email protected]:27017/demo?authSource=admin

#上面配置可写为以下配置
#spring.data.mongodb.database=demo
#spring.data.mongodb.host=192.168.10.102
#spring.data.mongodb.port=27017
#spring.data.mongodb.username=root
#spring.data.mongodb.password=admin
#spring.data.mongodb.authentication-database=admin

03.MongoDB的CRUD操作

用户类

@Data
@Document("User")
@AllArgsConstructor
public class User {
    @Id
    private Long id;
    private String name;
    private Date birthday;
    private int sex;
}

3.1插入

  • public T insert(T objectToSave):新增
 	@Autowired
    private MongoTemplate mongoTemplate;
    @GetMapping("/test1")
    public void insertDemo(){
         mongoTemplate.insert(new User(1314L,"zzj&mhz&wyq",new Date(),1));
    }

执行结果

在这里插入图片描述

3.2查询

数据

SpringBoot整合MongoDB完成CRUD操作(超详细)_第1张图片

常用API

  • public List findAll(Class entityClass) : 查询User文档的全部数据
  • public T findById(Object id, Class entityClass): 查询User文档id为id的数据
  • public List find(Query query, Class entityClass) : 根据query内的查询条件查询
	@Autowired
    private MongoTemplate mongoTemplate;

	@GetMapping("/test2")
    public void queryDemo(){
        System.out.println("=============查询所有====================");
        List<User> all = mongoTemplate.findAll(User.class);
        all.forEach(System.out::println);//方法引用
        System.out.println();
        
        System.out.println("===============根据id查询=======================");
        User user = mongoTemplate.findById(1314, User.class);
        System.out.println(user);
        System.out.println();
        
        System.out.println("===============条件查询=======================");
        //regex传正则表达式  查询sex为1并且name中包含zzj的用户
        String name="zzj";
        Pattern pattern = Pattern.compile(String.format("%s%s%s", "^.*", name, ".*$"),Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("sex").is(1).and("name").regex(pattern));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
        System.out.println();
        
        System.out.println("===============分页查询=======================");
        int pageSize=2,currentPage=1;
        long count = mongoTemplate.count(new Query(), User.class);
        List<User> userList = mongoTemplate.find(new Query().skip((currentPage - 1) * pageSize).limit(pageSize), User.class);
        System.out.println("记录数 = "+count);
        userList.forEach(System.out::println);
    }

执行结果

=============查询所有====================
User(id=1314, name=zzj&mhz&wyq, birthday=Sun May 22 22:37:14 CST 2022, sex=1)
User(id=6666, name=zzj, birthday=Sun May 22 22:37:15 CST 2022, sex=0)
User(id=8888, name=mhz, birthday=Sun May 22 22:37:15 CST 2022, sex=1)
User(id=9999, name=mhzzj, birthday=Sun May 22 22:37:15 CST 2022, sex=1)

===============根据id查询=======================
User(id=1314, name=zzj&mhz&wyq, birthday=Sun May 22 22:37:14 CST 2022, sex=1)

===============条件查询=======================
User(id=1314, name=zzj&mhz&wyq, birthday=Sun May 22 22:37:14 CST 2022, sex=1)
User(id=9999, name=mhzzj, birthday=Sun May 22 22:37:15 CST 2022, sex=1)

===============分页查询=======================
记录数 = 4
User(id=1314, name=zzj&mhz&wyq, birthday=Sun May 22 22:37:14 CST 2022, sex=1)
User(id=6666, name=zzj, birthday=Sun May 22 22:37:15 CST 2022, sex=0)

3.3修改

  • public UpdateResult upsert(Query query, Update update, Class entityClass):修改
	@Autowired
    private MongoTemplate mongoTemplate;
    
	@GetMapping("/test3")
    public void updateDemo(){
        Query query = new Query(Criteria.where("_id").is(1314));
        Update update=new Update();
        update.set("name","wyq&mhz&zzj&zdn");
        mongoTemplate.upsert(query,update,User.class);
    }

执行结果

在这里插入图片描述

3.4删除

  • public DeleteResult remove(Query query, Class entityClass):删除
	@Autowired
    private MongoTemplate mongoTemplate;
    
	@GetMapping("/test4")
    public void deleteDemo(){
        Query query = new Query(Criteria.where("_id").is(6666));
        mongoTemplate.remove(query,User.class);
    }

执行结果

在这里插入图片描述

你可能感兴趣的:(MongoDB,SpringBoot,mongodb,spring,boot,nosql,java)