Article directory
1. Goal
- 1 Use docker to install Mongo DB;
- 2 Remotely connect to the database, that is, you can connect through tools such as Robo 3T or DG;
- 3 Read and write the content in the database through the Spring boot program.
2.Environmental preparation
- 1 docker
- 2 Mongo mirror
- 3 IDEA
- 4 JAVA 11
3. Install MongoDB
3.1 Download Mongo DB image
docker pull mongo:latest
You can use docker images
to view the downloaded image
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mongo latest 40d4435de119 4 weeks ago 701MB
3.2 Running the container
docker run -itd --name mongo -p 27017:27017 mongo --auth
in
- p 27017:27017: Map the 27017 port of the container service to the 27017 port of the host.
- auth: A password is required to access the container service.
At this point you can check the running status of the container:
~ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
165d0cb0abd0 mongo:latest "docker-entrypoint.s…" 2 days ago Up 3 seconds 0.0.0.0:27017->27017/tcp mongo
3.3 Configuration
Enter the mongo container
$ docker exec -it mongo mongo admin
Create a user named admin with a password of 123456.
db.createUser({
user:'admin',pwd:'123456',roles:[ {
role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
Try to connect using the user information created above.
db.auth('admin', '123456')
3.4 Use
Enter mongo after trying to pass the command
➜ ~ docker exec -it mongo /bin/bash
root@165d0cb0abd0:/# mongo admin
MongoDB shell version v5.0.4
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session {
"id" : UUID("ea6eb8f4-e2a0-4ce8-b5dd-ca43302cc614") }
MongoDB server version: 5.0.4
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
> show dbs
>
As you can see, we cannot see the libraries we own through commands without entering a password.
> show dbs
> db.auth("admin","123456")
1
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
yytest 0.000GB
After passing the permission verification, you can operate the database.
3.5 Configure remote operation
At this time, if you use the Robo 3T tool to connect to the database and the connection fails, it is because the configuration file has not changed bindIp: 127.0.0.1, so you can only log in locally.
#进入容器
docker exec -it mongodb /bin/bash
#更新源
apt-get update
# 安装
apt-get install vim
# 修改 mongo 配置文件
vim /etc/mongod.conf.orig
Comment out bindIp: 127.0.0.1# bindIp: 127.0.0.1
or change it to bindIp: 0.0.0.0.
At this time, save and restart to connect remotely.
4. Spring data operation Mongo DB instance
Create a Spring boot project with the help of IDE A. Here I chose Kotlin to see how sweet this sugar is.
4.1 Pom.xml
Mainly adding spring-boot-starter-data-mongodb dependency
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>wu</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wu</name>
<description>wu</description>
<properties>
<java.version>11</java.version>
<kotlin.version>1.5.31</kotlin.version>
</properties>
<dependencies>
<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>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
4.2 entity entity class
package com.example.wu.entity
import lombok.Data
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
@Data
@Document("books")
data class Book(
@Id
val id: String,
val name:String,
val edition: Int
)
The @Document("books") annotation indicates that this entity corresponds to the collection named books in mongo db.
4.3 repository
package com.example.wu.dao
import com.example.wu.entity.Book
import org.springframework.data.mongodb.repository.MongoRepository
interface BookRepository: MongoRepository<Book, String> {
fun findByName(name: String): Book
}
Here you only need to inherit the interface and you can use various methods provided by the framework. Just pay attention to the naming convention of method names.
4.4 service
package com.example.wu.service
import com.example.wu.entity.Book
interface BookService {
fun findByName(bookName: String) : Book
}
package com.example.wu.service.impl
import com.example.wu.dao.BookRepository
import com.example.wu.entity.Book
import com.example.wu.service.BookService
import org.springframework.stereotype.Service
@Service
class BookServiceImpl(
private val bookRepository: BookRepository
) : BookService {
override fun findByName(name: String): Book {
return bookRepository.findByName(name)
}
}
4.5 web
package com.example.wu.web
import com.example.wu.entity.Book
import com.example.wu.service.BookService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import javax.websocket.server.PathParam
@RestController
class BookController(
private val bookService: BookService) {
@GetMapping("/book")
fun getBookByName(name: String): ResponseEntity<Book> {
var book = bookService.findByName(name)
return ResponseEntity.ok(book)
}
}
4.6 Start the portal
package com.example.wu
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class WuApplication
fun main(args: Array<String>) {
runApplication<WuApplication>(*args)
}
4.7 application.properties
server.port=10098
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=yytest
spring.data.mongodb.username=admin
spring.data.mongodb.password=123456
4.9 Testing
At this time, you can start it and perform a test to access data.
5. Dig a hole
The principle has not been analyzed yet, so let’s dig a hole first.