Talk about those things about MongoDB in detail

insert image description here

concept distinction

What is a relational database

A relational database is a database management system (DBMS) based on a relational model. In a relational database, data is stored in the form of a table. The table is composed of rows and columns. Rows represent data records, and columns represent data fields. Each table has a unique identifier, called a primary key, that uniquely identifies each row in the table.

The core concepts of a relational database include:

  1. Table: Data is organized in the form of tables, each table has a name and a set of columns that define the data type. Tables represent entities (such as people, things, events, etc.) and the relationships between entities.

  2. Row: Each row in the table represents a data record and contains data values ​​of different fields.

  3. Column: Each column in the table represents a data field and defines the type and format of the data.

  4. Primary Key: Each table has a primary key that uniquely identifies each row in the table. The primary key ensures the uniqueness and integrity of the data.

  5. Foreign Key (Foreign Key): Foreign keys are used to establish associations between different tables and represent the relationship between tables. Foreign keys usually refer to primary keys of other tables.

  6. SQL (Structured Query Language): Relational databases use SQL to perform data query, insert, update, and delete operations. SQL is a standardized query language for interacting with relational databases.

Some common examples of relational databases include:

  • MySQL
  • PostgreSQL
  • Oracle Database
  • Microsoft SQL Server
  • SQLite

Relational databases are known for their structured data models and wide range of applications. They are suitable for applications that require complex data relationships and rich queries, such as enterprise applications, financial systems, human resource management, etc. However, with the continuous growth of data and the diversification of application scenarios, many other types of databases have emerged, such as NoSQL databases, for processing unstructured and semi-structured data, and the MongoDB mentioned in this article is non-relational The database is also the protagonist of the article.

What is a non-relational database

Non-relational databases (NoSQL, Not Only SQL) are a type of database management system (DBMS), which use different data models and storage mechanisms than traditional relational databases. Non-relational databases are suitable for processing large-scale, highly distributed, unstructured or semi-structured data, and application scenarios that require higher scalability and flexibility.

Key features of non-relational databases include:

  1. Data model diversity: Non-relational databases support multiple data models, such as key-value pairs, documents, column families, graphs, etc., to accommodate different types of data.

  2. Distributed architecture: Many non-relational databases have a distributed architecture that scales horizontally, distributing data across multiple servers for high availability and better performance.

  3. Flexible mode: Non-relational databases generally do not require strict table structure definitions, allowing fields to be dynamically added and modified during data storage to adapt to changes in data modes.

  4. High scalability: Due to their distributed nature, non-relational databases can easily scale to handle large amounts of data and high concurrent requests.

  5. Adapt to big data: Non-relational databases are usually used to store and process large-scale data, such as social media data, log files, sensor data, etc.

Common non-relational database types include:

  1. Key-Value Stores: Data is stored in the form of key-value pairs, suitable for high-speed read and write operations, such as Redis and Amazon DynamoDB.

  2. Document Stores: Data is stored in documents similar to JSON or XML format, suitable for semi-structured data, such as MongoDB, Couchbase.

  3. Column Family Stores: Data is stored in the form of column families, suitable for large-scale distributed data, such as Apache Cassandra and HBase.

  4. Graph Databases: used to store and query graph data, suitable for complex data relationships, such as Neo4j, Amazon Neptune.

  5. Time Series Databases: dedicated to storing time series data, such as sensor data, log data, etc., such as InfluxDB and OpenTSDB.

  6. Search Engines: Used for full-text search and data analysis, such as Elasticsearch and Solr.

Non-relational databases are becoming more and more important in modern application development, especially in the fields of big data, cloud computing and distributed systems. The reason why we introduce the MongoDB database this time is also because the system development requirements require chat records to be For saving, in view of the large amount of data, the MongoDB architecture is considered.

Introduction to the main character MongoDB

MongoDB is an open source, document-oriented, non-relational database management system (NoSQL DBMS), known for its flexibility, scalability, and powerful query capabilities. MongoDB is designed to meet the needs of massive data, high availability, and complex data models in modern applications. Following are some important features and concepts of MongoDB:

  1. Document database: MongoDB uses documents to represent data. Documents are similar to JSON-formatted data structures and can contain various types of data, such as strings, numbers, dates, arrays, and nested documents.

  2. Document-oriented: MongoDB is a document-oriented database, and each document has a unique identifier (often called _id), which is used to uniquely identify the document.

  3. High scalability: MongoDB supports horizontal expansion, and can distribute data to multiple servers through sharding to achieve higher storage capacity and performance.

  4. Dynamic mode: MongoDB does not require strict table structure definition, and documents can freely add and modify fields to adapt to changes in data mode.

  5. Powerful query language: MongoDB supports a rich query language, which can perform complex query operations, including filtering, sorting, projection, aggregation, etc.

  6. Index support: MongoDB supports various types of indexes, including single-field indexes, composite indexes, text indexes, geospatial indexes, etc., to speed up query operations.

  7. Replication and high availability: MongoDB supports data replication and automatic failover to ensure high availability and redundancy of data.

  8. Data storage: MongoDB stores data in collections, each of which contains a set of documents. Collections are similar to tables in relational databases.

  9. Applicable scenarios: MongoDB is suitable for scenarios that require storage and processing of semi-structured or unstructured data, such as big data, real-time data analysis, content management systems, log records, and user personalized recommendations.

Introduction to MongoDB installation

Install MongoDB on CentOS

Here are the detailed steps to install MongoDB on CentOS:

  1. Update the system:
    Open a terminal, and log in as root or a user with sudo privileges, first update the system packages to ensure that the system is up to date:
sudo yum update
  1. Adding the MongoDB repository:
    MongoDB provides an official YUM repository which can be added to your system using the following steps:
sudo vi /etc/yum.repos.d/mongodb-org.repo

In the editor, add the following (save and exit the editor):

[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc
  1. Install MongoDB:
    Install the MongoDB package with the following command:
sudo yum install -y mongodb-org
  1. Start the MongoDB service:
    After the installation is complete, you can start the MongoDB service and set it to start automatically:
sudo systemctl start mongod
sudo systemctl enable mongod
  1. Verify that MongoDB has started correctly:
    Run the following command to verify that MongoDB has started successfully:
sudo systemctl status mongod

You should see the MongoDB service status as "active (running)".

  1. Connect to the MongoDB Shell:
    To interact with the database using the MongoDB Shell, run the following commands:
mongo

This will connect to the local MongoDB server's shell.

docker install MongoDB

As you all know my habits, the installation method of docker is definitely indispensable. It
is a convenient way to install MongoDB and run it in a Docker container. Let us introduce in detail how to install and run MongoDB in Docker.

  1. Install Docker :

    If you do not have Docker installed, follow the steps below to install Docker on your operating system:

    • For Linux users, you can choose an appropriate installation method according to your distribution, usually using a package management tool (such as aptor yum) to install Docker.
    • For Windows users, you can download and run the installer from the official Docker website.
    • For macOS users, you can download and run the Docker Desktop installer from the official Docker website.
  2. Pull the MongoDB image :

    Open a terminal (or command line interface) and execute the following command to pull the official MongoDB image from Docker Hub:

    docker pull mongo
    
  3. Run the MongoDB container :

    Use the following commands to create and run a MongoDB container. This will create a MongoDB container named "my-mongodb" and bind it to port 27017 on the host machine. You can adjust the container name and port bindings yourself as needed.

    docker run --name my-mongodb -p 27017:27017 -d mongo
    

    This command will run the MongoDB container in background mode. To stop the container, you can use docker stopthe command:

    docker stop my-mongodb
    

    To delete a container, you can use docker rmthe command:

    docker rm my-mongodb
    
  4. Connect to MongoDB container :

    To connect to the Mongo shell of a running MongoDB container, the following command can be used:

    docker exec -it my-mongodb mongo
    

    This will enter the Mongo shell where MongoDB commands can be executed.

Install MongoDB on Win system

To install MongoDB on a Windows system, follow these steps:

  1. Download the MongoDB installation package:
    Go to the MongoDB official website (https://www.mongodb.com/try/download/community-kubernetes-operator) to download the latest version of the MongoDB installation package. Make sure to choose the version that matches your operating system.
    insert image description here

  2. Install MongoDB:
    Double-click the downloaded installation package and follow the instructions of the installation wizard to complete the installation process. You can choose a custom installation option, but for most users, the default options will do just fine.

  3. Configure the MongoDB environment variable:
    add the MongoDB installation path to the system environment variable, so that you can access MongoDB through the command line in any directory. Add the installation path (C:\Program Files\MongoDB\Server<version number>\bin by default) to the Path variable in your system environment variables.

  4. Create a data directory:
    Create a data directory on the location of your choice to store MongoDB data files. For example, you can create a folder called db under the C:\data directory.

  5. Configure the MongoDB service:
    Open a command prompt (CMD) or PowerShell, and navigate to the MongoDB installation directory (for example: C:\Program Files\MongoDB\Server<version number>\bin).

    Run the following command to start the MongoDB server:

    mongod --dbpath <数据目录路径>
    

    Please <数据目录路径>replace with the path of the data directory you created in step 4.

  6. Connect to MongoDB:
    Open another Command Prompt or PowerShell window and navigate to the directory where MongoDB is installed (for example: C:\Program Files\MongoDB\Server<version number>\bin).

    Run the following command to connect to MongoDB:

    mongo
    

Please note that if you do not follow the above steps, but execute the exe directly in the installation directory
insert image description here

Then you need to create a /data/db directory in the root path of the D disk, otherwise it will crash! ! !
insert image description here

MongoDB does not write environment variables by default. You need to configure it yourself, so I won’t repeat it here! ! !

Introduction to MongoDB

In MongoDB, the establishment of collections (similar to tables in relational databases) is dynamic, so there is no need to explicitly define the table structure as in relational databases. Just insert a document (similar to a record in a relational database), and MongoDB will automatically create the collection and define the fields according to the structure of the document. Command execution We can use the Navicat tool to connect
insert image description here

Following is the syntax and examples for creating collections and inserting documents in MongoDB:

easy to use

  1. Create collection and insert documents:
// 使用insertOne插入文档并创建集合
db.collectionName.insertOne({
    
     field1: "value1", field2: "value2", ... })

Example:

db.students.insertOne({
    
     name: "李红", age: 25, major: "Computer Science" })
db.students.insertOne({
    
     name: "张飞", age: 22, major: "Biology" })

insert image description here

  1. Query for documents in a collection:
// 查询集合中的所有文档
db.collectionName.find()

// 查询特定条件的文档
db.collectionName.find({
    
     field: "value" })

Example:

// 查询所有学生
db.students.find()

// 查询年龄大于等于 25 岁的学生
db.students.find({
    
     age: {
    
     $gte: 25 } })
  1. Update docs:
// 使用updateOne更新单个文档
db.collectionName.updateOne({
    
     condition }, {
    
     $set: {
    
     field: "new value" } })

// 使用updateMany更新多个文档
db.collectionName.updateMany({
    
     condition }, {
    
     $set: {
    
     field: "new value" } })

Example:

// 更新学生的专业
db.students.updateOne({
    
     name: "张飞" }, {
    
     $set: {
    
     major: "Engineering" } })
  1. Delete document:
// 使用deleteOne删除单个文档
db.collectionName.deleteOne({
    
     condition })

// 使用deleteMany删除多个文档
db.collectionName.deleteMany({
    
     condition })

Example:

// 删除专业为"Biology"的学生
db.students.deleteMany({
    
     major: "Biology" })

Let's take another example, assuming that we are developing a simple blogging platform, we can use MongoDB to store blog posts and comments. In this example of a complex business, we will cover the following:

  1. Create collections and insert documents
  2. Query and filter data
  3. update document
  4. use index

1. Create a collection and insert documents:

First, we create a collection to store blog posts, each post containing title, content and publication date:

// 创建博客集合并插入帖子文档
db.blogPosts.insertOne({
    
    
  title: "MongoDB的相关介绍   ——IT小辉同学",
  content: "MongoDB 是一个非关系型数据库",
  publishDate: new Date("2023-08-01"),
  comments: []
})

2. Query and filter data:

Now, we query the posts in the blog collection and filter for posts with a publish date within a certain range:

// 查询发布日期在特定范围内的帖子
db.blogPosts.find({
    
    
  publishDate: {
    
     $gte: new Date("2023-08-01"), $lt: new Date("2023-08-10") }
})

3. Update the documentation:

Suppose a post has received a new comment, we can add the comment to the post's comments array:

// 更新帖子,添加新评论
db.blogPosts.updateOne(
  {
    
     title: "MongoDB的相关介绍,很有意思奥   ——IT小辉同学" },
  {
    
    
    $push: {
    
    
      comments: {
    
    
        author: "User123",
        text: "MongoDB,我们一起学习!",
        timestamp: new Date()
      }
    }
  }
)

4. Use the index:

To improve query performance, we can create indexes to speed up certain query operations. For example, to speed up queries that search for posts by title, we can create an index on the title field:

// 创建标题字段的索引
db.blogPosts.createIndex({
    
     title: "text" })

This is a simplified example showing how to handle the complex business scenario of blog posts and comments in MongoDB. In actual business, more situations may need to be dealt with, such as user authentication, data verification, user relationship, etc. The flexibility and functionality of MongoDB can adapt to various complex business needs.

Please note that the syntax of MongoDB uses JSON, which is what we often call objects in Java, so data and queries are in the form of JSON.

complex grammar

When you need to perform more complex addition, deletion, modification and query operations, MongoDB provides rich query, update and aggregation functions to meet your needs. Here is a more complex example, covering multi-condition query, update and aggregation operations:

1. Multi-condition query:

Assume that you want to query posts whose publication date is within a specific range and whose title contains a specific keyword:

db.blogPosts.find({
    
    
  publishDate: {
    
     $gte: new Date("2023-08-01"), $lt: new Date("2023-08-10") },
  title: {
    
     $regex: "MongoDB" }
})

2. Multi-condition update:

Update the comments of a post, replacing the text in all comments by the specified author with the new text:

db.blogPosts.updateMany(
  {
    
     "comments.author": "User123" },
  {
    
     $set: {
    
     "comments.$[].text": "新文本" } }
)

3. Use aggregation:

Aggregate operations allow you to do data manipulation and transformation. Suppose you want to count the number of comments per post and sort by descending number of comments:

db.blogPosts.aggregate([
  {
    
    
    $project: {
    
    
      title: 1,
      numberOfComments: {
    
     $size: "$comments" }
    }
  },
  {
    
    
    $sort: {
    
     numberOfComments: -1 }
  }
])

The above code uses an aggregation pipeline, first by $projectextracting the title and number of comments for each post, and then $sortsorting by descending number of comments.

4. To delete multiple documents:

Suppose you want to delete all posts with comments below a specified value:

db.blogPosts.deleteMany({
    
    
  comments: {
    
     $size: {
    
     $lt: 5 } }
})

This will delete all posts with less than 5 comments.

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/132267063