Attention can view more fans exclusive blog~

preface

ElasticSearch pinyin ElasticSearch pinyin ElasticSearch pinyin ElasticSearch pinyin ElasticSearch pinyin ElasticSearch pinyin ElasticSearch pinyin These are some of the middleware that are very popular these days.

ElasticSearch portal:

Spring Boot uses Docker to integrate ElasticSearch

Spring Boot uses Docker to integrate ElasticSearch IK segmentation and pinyin search

Introduction to the

MongoDB is a document database, which means it stores data in JSON-like documents. In our opinion, this is the most natural way to think about data and is more expressive and functional than the traditional row/column model.

  1. Rich JSON documentation
    • The most natural and efficient way to process data.
    • Arrays and nested objects are supported as values.
    • Allows flexible and dynamic patterns.
  2. Powerful query language
    • A rich and expressive query language that allows you to filter and sort by any field, no matter how nested you are in the document.
    • Support for aggregation and other modern use cases, such as geo-based search, graph search, and text search.
    • The query itself is JSON, so it’s easy to compose. The join string is no longer required to generate SQL queries dynamically.
  3. All the features of relational databases, and more…
    • Distributed multi-document ACID transactions with snapshot isolation.
    • Query joins are supported.
    • Two types of relationships, not one: reference and embedded.

Applicable scenario

The primary goal of MongoDB is to bridge the gap between the key/value store approach, which provides high performance and high scalability, and traditional RDBMS systems, which are rich in functionality.

  1. Web site data: Mongo is ideal for real-time insertion, update, and query, with the replication and high scalability required for real-time web site data storage.
  2. Caching: Because of its high performance, Mongo is also suitable as a caching layer for information infrastructure. After the system restarts, the persistent cache layer built by Mongo avoids overloading the underlying data source.
  3. Large, low-value data: It can be expensive to store some data in a traditional relational database, but programmers often choose to store it in traditional files.
  4. Highly scalable scenarios: Mongo is ideal for databases consisting of dozens or hundreds of servers, and Mongo’s roadmap already includes built-in support for the MapReduce engine.
  5. For object and JSON data storage: Mongo’s BSON data format is very suitable for storage and query in document format.

Install the mongo

// Docker pull mongo // check whether docker images are pulled successfully // Run the image, 27017 docker run -itd --name mongo -p 27017:27017 mongo // check whether the container is successfully started docker ps // enter the container docker exec -it mongo Use mydb // createCollection db.createcollection ('test') // insert data db.test.insert({id:1,name:' David ',age:18})Copy the code

The previous pull operation is not screenshots, below is the boot and setup part of the screenshots for reference

Spring Boot integrates MongoDB

  1. Create a New Spring Boot project using IDEA and select Web and mongodb
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Copy the code
  1. The configuration file is modifiedapplication.yml
spring:
  data:
    mongodb:
      uri: Mongo: / / 127.0.0.1:27017 /
      database: mydb
  application:
    name: mongo-demo
server:
  port: 8080

Copy the code
  1. Now let’s write some code to manipulate MongoDB.
  2. Write code to manipulate MongoDB

UserEntity code

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "test")
public class UserEntity {

    @Id
    private Long id;

    private String name;

    private Integer age;

}

Copy the code

UserRepository code

import com.example.mongo.entity.UserEntity;

import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface UserRepository extends MongoRepository<UserEntity.Long> {

    List<UserEntity> findByNameLike(String name);

}

Copy the code

UserService code

import com.example.mongo.entity.UserEntity;

import java.util.List;

public interface UserService {

    void save( UserEntity userEntity );

    void save( List<UserEntity> userEntity );

    void delete( Long id );

    List<UserEntity> findByName( String name );

    UserEntity findById( Long id );

}
Copy the code

UserServiceImpl code

import com.example.mongo.entity.UserEntity;
import com.example.mongo.repository.UserRepository;
import com.example.mongo.service.UserService;

import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Override
    public void save( UserEntity userEntity ) {
        userRepository.save(userEntity);
    }

    @Override
    public void save( List<UserEntity> userEntity ) {
        userRepository.saveAll(userEntity);
    }

    @Override
    public void delete( Long id ) {
        userRepository.deleteById(id);
    }

    @Override
    public List<UserEntity> findByName( String name ) {
        return userRepository.findByNameLike(name);
    }

    @Override
    public UserEntity findById( Long id ) {
        return userRepository.findById(id).orElse(newUserEntity()); }}Copy the code

MongoApplicationTests

@SpringBootTest
class MongoApplicationTests {

    @Resource
    private UserService userService;

    @Test
    void save(a) {
        List<UserEntity> users = new ArrayList<>();
        for (int i = 1; i <= 20; i++) {
            UserEntity user = UserEntity.builder().id((long) i).name("Davids" + i).age(i).build();
            users.add(user);
        }
        userService.save(users);
    }

    @Test
    void find(a) {
        UserEntity byId = userService.findById(1L);
        System.out.println(byId);
        List<UserEntity> dav = userService.findByName("1");
        dav.forEach(System.out::print);
    }

    @Test
    void update(a) {
        userService.save(UserEntity.builder().id(1L).name("Davids edit").age(16).build());
    }

    @Test
    void delete(a) {
        userService.delete(1L); }}Copy the code

conclusion

When MongoDB uses Repository, we can write methods by method name as shown in the following figure. For example, findByNameLike is a fuzzy query based on the name. It is quite interesting