Springboot integrated mongodb quick start demo

HBLOG
3 min readFeb 1, 2024

--

一、mongodb introduce

MongoDB is a product between a relational database and a non-relational database. It is the most feature-rich among non-relational databases and is most similar to a relational database. The data structure it supports is very loose, in a bson format similar to json, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to an object-oriented query language. It can almost implement most functions similar to single-table queries in relational databases, and it also supports indexing of data.

二、mongodb environment setup

use docker-compose to build,the config file as follower:

version: '3'
# bridge mongo -> communicate easy
networks:
mongo:
services:
# mongodb
mongodb:
image: registry.cn-hangzhou.aliyuncs.com/zhengqing/mongo:4.4.6 #
restart: unless-stopped
container_name: mongodb
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: 123456
MONGO_DATA_DIR: /data/db
MONGO_LOG_DIR: /data/logs
# volumes:
# - ./mongodb/db:/data/db
# - ./mongodb/log:/data/log
ports:
- "27017:27017"
networks:
- mongo
# vision gui tools
adminmongo:
image: mrvautin/adminmongo
restart: unless-stopped
container_name: adminmongo
environment:
- HOST=0.0.0.0
depends_on:
- 'mongodb'
links:
- mongodb
ports:
- "1234:1234"
networks:
- mongo

start docker-compose

docker-compose -f docker-compose-mongodb.yml -p mongodb up -d

access url:[`http://ip:1234`](http://127.0.0.1:1234)

Connection string:`mongodb://admin:123456@ip:27017`

三、Code Project

pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mongodb</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- SpringBoot MongoDB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>

</dependencies>
</project>

entity

package com.et.mongodb.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.data.mongodb.core.mapping.MongoId;
import java.util.Date;
@Data
@ToString
@Accessors(chain = true)
public class User {
/**
* use @MongoID can specify _id primary key more clearly
*/
@MongoId
private String id;
private String name;
private String sex;
private Integer salary;
private Integer age;
@JsonFormat( pattern ="yyyy-MM-dd", timezone ="GMT+8")
private Date birthday;
private String remake;
private Status status;
}
package com.et.mongodb.entity;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
@ToString
@Accessors(chain = true)
public class Status {
private Integer weight;
private Integer height;
}

start class

package com.et.mongodb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

application.yaml

server:
port: 8088
spring:
data:
mongodb:
uri: mongodb://admin:123456@127.0.0.1:27017/admin
# need username and password
#uri: mongodb://username:password@ip:port/admin
#no nedd username and password
#uri: mongodb://ip:port/admin

Code Repository

四、Test

package com.et.mongodb;
import com.et.mongodb.entity.Status;
import com.et.mongodb.entity.User;
import com.mongodb.client.model.Indexes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class MongodbTests {
private Logger log = LoggerFactory.getLogger(getClass());
private static final String COLLECTION_NAME = "users";
@Resource
private MongoTemplate mongoTemplate;

@Test
public void createIndex() {
String field = "name";
// create index
mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field));
}
@Test
public void insert() {
// set user info
User user = new User()
.setId("10")
.setAge(22)
.setSex("man")
.setRemake("nothing")
.setSalary(1500)
.setName("zhangsan")
.setBirthday(new Date())
.setStatus(new Status().setHeight(180).setWeight(150));
// insert user info,throw exception when the row record is exist
User newUser = mongoTemplate.insert(user, COLLECTION_NAME);
// output result
log.info("user info:{}", newUser);
}

}

五、reference

--

--