springboot整合Mongodb
一、安装Mongodb
到官网安装 https://www.mongodb.com/
二、启动
在bin的目录下打开cmd,启动服务端,(如:F:\Program Files (x86)\mongodb\bin) 端口号:27017
mongod --dbpath=..\data\db
启动客户端**(如:F:\Program Files (x86)\mongodb\bin)** 端口号:27017 都是默认localhost和27017
mongo
安装mongo的客户端-robo3t-1.4.4
打开后登录(同MySQL)
基础操作
建库建表同MySQL
//查询所有
db.getCollection('book').find({})
//条件查询
// db.book.find({type:"微服务"})
//添加文档
// db.book.save({"name":"springboot",type:"微服务"})
//删除文档
// db.book.remove({type:"微服务"})
//修改文档,如果多条相同,只修改头一条
db.book.update({name:"springboot"},{$set:{name:"springboot,success"}})
三、整合spring boot
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置访问MongoDB的URI
spring:
data:
mongodb:
uri: mongodb://localhost/itlyd
客户端读写mongodb,用MongoTemplate
package com.lyd;
import com.lyd.domain.Book;
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 java.util.List;
@SpringBootTest
class Springboot17MongodbApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void contextLoads() {
Book book = new Book();
book.setId(1);//id一样会覆盖
book.setName("springboot");
book.setType("微服务");
book.setDescription("1234567890");
mongoTemplate.save(book);//用对象去存,然后在调用保存
}
@Test
void find(){
List<Book> all = mongoTemplate.findAll(Book.class);
Iterator<Book> it = all.iterator();//复习一下迭代输出
while (it.hasNext()){
Book b = new Book();
b = it.next();
System.out.println(b.getId() + " " + b.getName() + " " + b.getType() + " " + b.getDescription());
}
}
}