集成
- 依赖
spring-boot-starter-data-mongodb
- 设置 uri
- 创建
@Document(collection = "table")
- 创建
MongoRepository
spring:
data:
mongodb:
uri: mongodb://order:order@localhost:27017/order
@Data
@Builder
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "users")
public class UserMongo {
@Id
private String id;
private String name;
private int age;
}
public interface UserMongoRepository extends MongoRepository<UserMongo, String> {
UserMongo findByName(String name);
}
测试
@Slf4j
@SpringBootTest
public class UserMongoRepTest {
@Autowired
private UserMongoRepository userMongoRepository;
@Test
public void mongoTest() {
userMongoRepository.save(new UserMongo("jxch", 26));
UserMongo jxch = userMongoRepository.findByName("jxch");
log.info(JSON.toJSONString(jxch));
}
}
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<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>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
数据库部署
version: '3.8'
services:
mongodb:
image: mongo
restart: unless-stopped
ports:
- 27017:27017
volumes:
- ./data/mongodb_data:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: pw
use order
db.createUser({
user: "order",
pwd: "order",
roles: [
{ role: "readWrite", db: "order" },
{ role: "dbAdmin", db: "order" },
{ role: "userAdmin", db: "order" },
{ role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "restore", db: "admin" },
{ role: "backup", db: "admin" }
]
})
db.usersTest.insertOne({name: "John", age: 30})