There is already MySQL, why learn MongoDB?

In three minutes, through this article you will learn

1. Main features of MongoDB

2. Advantages and disadvantages of MongoDB, maximize strengths and avoid weaknesses

3. When to choose MongoDB? Why use it?

4. Comparison of MongoDB and MySQL keywords

5. Download and install MongoDB

6. Java integrates MongoDB to realize addition, deletion, modification and query

The difference between MongoDB and MySQL

The data models are different: MySQL is a relational database, while MongoDB is a document database. MongoDB's data model is more flexible, can store unstructured data, and is suitable for processing large amounts of semi-structured data.

Handling large amounts of data: MongoDB can handle massive amounts of data, while MySQL may have performance bottlenecks when processing large amounts of data. MongoDB's distributed architecture can easily scale to multiple nodes to handle large amounts of data.

High availability: MongoDB has high availability and fault tolerance, and can automatically distribute data among multiple nodes to ensure data reliability and availability.

Suitable for cloud computing: MongoDB is ideal for the era of cloud computing and can be easily deployed and managed in the cloud, while MySQL requires more configuration and management.

Suitable for real-time applications: MongoDB supports real-time data processing and real-time query, and is suitable for real-time application scenarios that require fast response.

MongoDB main features

Document-oriented data model: MongoDB is a document-based database. Data is stored in the form of documents. Each document can contain different fields and values. This data model is more flexible than traditional relational databases.

High performance: MongoDB has high-performance read and write capabilities, and supports high concurrency and fast data query.

Distributed architecture: MongoDB supports distributed architecture, which can be easily extended to multiple nodes to handle large amounts of data.

High availability: MongoDB has high availability and fault tolerance, and can automatically distribute data among multiple nodes to ensure data reliability and availability.

Index support: MongoDB supports various types of indexes, including single-field indexes, compound indexes, full-text indexes, etc., which can improve the efficiency of data query.

Powerful query language: MongoDB supports a powerful query language, including aggregation pipeline, geospatial query, text search, etc., which can meet different query requirements.

Scalability: MongoDB can be easily extended to multiple nodes to handle large amounts of data and high concurrent requests.

Open source: MongoDB is an open source database that can be used and modified for free.

Advantages and disadvantages of MongoDB, maximize strengths and avoid weaknesses

Advantages of MongoDB:

  1. Flexible data model: MongoDB's document data model is very flexible, can store semi-structured data, and is suitable for processing different types of data.

  2. High performance: MongoDB has high-performance read and write capabilities, and supports high concurrency and fast data query.

  3. Distributed architecture: MongoDB supports distributed architecture, which can be easily extended to multiple nodes to handle large amounts of data.

  4. High availability: MongoDB has high availability and fault tolerance, and can be automatically distributed among multiple nodes to ensure data reliability and availability.

  5. Index support: MongoDB supports various types of indexes, including single-field indexes, compound indexes, full-text indexes, etc., which can improve the efficiency of data query.

  6. Powerful query language: MongoDB supports a powerful query language, including aggregation pipeline, geospatial query, text search, etc., which can meet different query requirements.

  7. Scalability: MongoDB can be easily extended to multiple nodes to handle large amounts of data and high concurrent requests.

  8. Open source: MongoDB is an open source database that can be used and modified for free.

Disadvantages of MongoDB:

  1. Does not support transactions: MongoDB does not support transactions in earlier versions. Although transactions are already supported in the latest version, it is still insufficient compared to traditional relational databases.

  2. High memory usage: When MongoDB processes a large amount of data, it needs to occupy a lot of memory. If the memory is insufficient, it may cause performance degradation.

  3. Cautious database design is required: the flexibility of MongoDB also brings certain challenges. The database structure needs to be carefully designed to avoid data redundancy and inconsistency.

  4. Large storage space: MongoDB needs to occupy a large storage space when storing data. If the amount of data is large, it may lead to high storage costs.

To sum up, MongoDB has the advantages of flexible data model, high performance, distributed architecture, high availability, index support, powerful query language, scalability and open source, but does not support transactions, high memory usage, and database design Disadvantages such as the need to be cautious and the large storage space occupied need to be paid attention to.

When to choose MongoDB? Why use it?

(1) Game scene

Use MongoDB to store game user information, equipment, points, etc., and store them directly in the form of embedded documents, which is convenient for query and update.

(2) Logistics scene

Use MongoDB to store order information, order status, and logistics information. The order status is iterated rapidly during the delivery process and stored in the form of an embedded array in MongoDB. All changes in the order can be found out in one query, which is amazing plus.

(3) Social scene

Use MongoDB to store user information and circle of friends information, and realize nearby people and positioning functions through geographic location index.

(4) IoT scenarios

Use MongoDB to store device information, log information reported by the device, and perform multi-dimensional analysis on these information.

(5) Live video

Use MongoDB to store user information and like interaction information.

Comparison of MongoDB and MySQL keywords

download and install

The following are the steps to download and install MongoDB:

  1. Visit the MongoDB official website (https://www.mongodb.com/), and click the "Download" button.

  2. Under "Community Server", select the version that suits your operating system, such as Windows, macOS, or Linux.

  3. After the download is complete, double-click the installer and follow the prompts to install it.

  4. After the installation is complete, open the command line tool and enter the "mongo" command. If information such as "MongoDB shell version xxx" appears, the installation is successful.

  5. If you need to create a database locally, you can enter the "mongod" command in the command line tool to start the MongoDB service.

  6. Enter "http://localhost:27017/" in the browser to access the web management interface of MongoDB.

Precautions:

  1. During the installation process, you need to select the installation path and data storage path. It is recommended to select the default path.

  2. After the installation is complete, you need to add the MongoDB bin directory to the system environment variable so that you can use the MongoDB command on the command line.

  3. Before starting the MongoDB service, you need to create a data storage directory, which can be created by entering the "mkdir data\db" command on the command line.

  4. When using MongoDB, you need to connect to the MongoDB service first. You can enter the "mongo" command on the command line to connect to the local MongoDB service.

Java integrates MongoDB to realize addition, deletion, modification and query

Integrate Spring Boot and MongoDB to realize the addition, deletion, modification and query of students. The steps are as follows:

  1. Create a Spring Boot project and add MongoDB dependencies.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Then configure the connection information:

Add MongoDB connection information in the or application.propertiesfile , for example:application.yml

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydb

Among them, host and port are the host name and port number of MongoDB respectively, and database is the name of the database to be connected.

If MongoDB requires authentication, you also need to add the following configuration:

spring.data.mongodb.username=myuser
spring.data.mongodb.password=mypassword

Among them, username and password are the username and password of MongoDB respectively.

  1. Create a student entity class.

@Document(collection = "student")
public class Student {
    @Id
    private String id;
    private String name;
    private int age;
    // 省略getter和setter方法
}
  1. Create a student Repository interface.

@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}
  1. Create student Service interface and implementation class.

public interface StudentService {
    List<Student> findAll();
    Student findById(String id);
    void save(Student student);
    void deleteById(String id);
}

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(String id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public void save(Student student) {
        studentRepository.save(student);
    }

    @Override
    public void deleteById(String id) {
        studentRepository.deleteById(id);
    }
}
  1. Create a student Controller class.

@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("")
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @GetMapping("/{id}")
    public Student findById(@PathVariable String id) {
        return studentService.findById(id);
    }

    @PostMapping("")
    public void save(@RequestBody Student student) {
        studentService.save(student);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable String id, @RequestBody Student student) {
        student.setId(id);
        studentService.save(student);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable String id) {
        studentService.deleteById(id);
    }
}

Full code example:

Student.java

@Document(collection = "student")
public class Student {
    @Id
    private String id;
    private String name;
    private int age;
    // 省略getter和setter方法
}

StudentRepository.java

@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}

StudentService.java

public interface StudentService {
    List<Student> findAll();
    Student findById(String id);
    void save(Student student);
    void deleteById(String id);
}

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(String id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public void save(Student student) {
        studentRepository.save(student);
    }

    @Override
    public void deleteById(String id) {
        studentRepository.deleteById(id);
    }
}

StudentController.java

@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("")
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @GetMapping("/{id}")
    public Student findById(@PathVariable String id) {
        return studentService.findById(id);
    }

    @PostMapping("")
    public void save(@RequestBody Student student) {
        studentService.save(student);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable String id, @RequestBody Student student) {
        student.setId(id);
        studentService.save(student);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable String id) {
        studentService.deleteById(id);
    }
}

Summarize

MongoDB is a document-based NoSQL database with high performance, high availability, and scalability. It uses BSON format to store data, supports complex query and aggregation operations, and also provides functions such as distributed locks and transactions. The data model of MongoDB is very flexible and can be freely designed according to the needs of the application. In Spring Boot, you can use MongoDB by introducing MongoDB dependencies and configuring connection information, and use Spring Data MongoDB to operate the MongoDB database.

Guess you like

Origin blog.csdn.net/weixin_39570751/article/details/130866048