Linux MongoDB installation and configuration

Table of contents

MongoDB overview

MongoDb installation and deployment

MongoDB set password

MongoDB operation commands and instructions

Configuration file description

Backup operation

Restore operation

MongoDB practical scenario application



MongoDB overview


MongoDB is a non-relational database management system that uses a document model to store data. Documents in MongoDB are similar to JSON objects and can contain key-value pairs and nested documents. MongoDB provides a powerful query language, aggregation framework, indexes, and calculations that run directly on the data store.

MongoDB is widely used in many fields, especially in web applications and big data fields. It is highly scalable and flexible and can handle a variety of data types. Additionally, MongoDB provides a range of tools and libraries to facilitate developers to use it in their applications.

MongoDB can store important data of the web content management system, such as page and article content, tags, etc., as well as user-related data.

MongoDb installation and deployment


The following are the detailed steps to install and deploy MongoDB on CentOS 7:

1. Add the official library of MongoDB.

Execute the following command to add the official repository of MongoDB:

```

sudo vim /etc/yum.repos.d/mongodb-org-4.4.repo

```

Add the following content to the file:

```

[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

```

Save and exit.

2. Install MongoDB.

Execute the following command to install MongoDB:

```

sudo yum install mongodb-org -y

```

3. Configure MongoDB.

Open the MongoDB configuration file:

```

sudo vim /etc/mongod.conf

```

Find and modify the following content in the file:

- `bindIp`: The bound IP address. The default is `127.0.0.1`, which is local access. If remote access is required, it needs to be changed to `0.0.0.0`.

- `port`: port number. The default is `27017`, which can be modified according to actual needs.

Save and exit.

4. Start MongoDB.

Execute the following command to start MongoDB:

```

sudo systemctl start mongod

```

5. Set MongoDB to serve the system.

Execute the following command to set MongoDB as a system service:

```

sudo systemctl enable mongod

```

You can check the status of the service using the following command:

```

sudo systemctl status mongod

```

6. Log in to MongoDB.

Log in to MongoDB using the following command:

```

mongo

```

You can check the version of MongoDB using the following command:

```

db.version()

```

If MongoDB is installed successfully, the version number of MongoDB should be output.

The above are the detailed steps for installing and deploying MongoDB on CentOS 7.

MongoDB set password


After installing MongoDB, there is no password by default. You can directly log in to MongoDB to start using it. However, in a production environment, it is highly recommended to configure MongoDB's security settings, such as enabling authentication, etc.

If you need to set up an administrator account and set a password for it, follow these steps:

1. Log in to MongoDB using mongo shell.

2. Enter the admin database:

```

use admin

```

3. Create an administrator account:

```

db.createUser({ user: "admin", pwd: "yourpassword", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })

(Where "yourpassword" is the password you want to set.)

[This is to create a user named "admin" in the MongoDB database, the user's password is "yourpassword", (the password can be changed by yourself) and grant the user permission to perform user management operations on all databases. Specifically, the user was granted the "userAdminAnyDatabase" role in the "admin" database, which allows the user to create, modify, and delete users on any database.

```

[The information reported is that this is a MongoDB database command, indicating that a user named "admin" has been successfully added, and this user has the authority to perform user management operations on any database. Specifically, this user can create, modify, and delete other users, as well as grant and revoke permissions from other users.

4. Exit the mongo shell and restart the mongod process:

```

sudo systemctl stop mongod

sudo systemctl start mongod

```

5. Use the mongo shell to log in to MongoDB again, and use the following command to verify the login:

```

mongo -u admin -p yourpassword --authenticationDatabase admin

```

[This is the command to connect to the MongoDB database, where:

- `-u admin` means to use the user with the user name "admin" to connect;
- `-p yourpassword` means to use the user with the password "yourpassword" to connect;
- `--authenticationDatabase admin` means the authentication database is "admin" ".

This command will prompt you to enter a password. After entering the correct password, you can connect to the MongoDB database. 】 

The above are the steps to create and set up an administrator account in MongoDB. Pay attention to the security and complexity of the password. If you do not set up an administrator account, MongoDB does not have a password by default.

MongoDB operation commands and instructions


The following are common command operations and instructions for MongoDB:

1. show dbs

Displays a list of all databases.

2. use <dbname>

Select the database to use. If the database does not exist, a new database is created.

3. db.<collection>.find()

Find documents in a specified collection, for example:

```

db.users.find()

```

[You must first create the document before you can find it. Complete point 4 first]

4. db.<collection>.insertOne()

Insert a new document into the specified collection, for example:

```

db.users.insertOne( { name: "John", age: 30, city: "New York" } )

```

5. db.<collection>.updateOne()

Update a document in the specified collection, for example:

```

db.users.updateOne(

   { name: "John" },

   { $set: { city: "San Francisco" } }

)

```

[Feedback information indicates: This is the return result of a MongoDB database operation, indicating that a document has been successfully updated, where:

- `acknowledged` indicates whether the operation is confirmed, here true indicates confirmation.
- `matchedCount` indicates the number of documents that meet the update conditions. Here, 1 indicates that one document has been updated.
- `modifiedCount` indicates the number of documents actually modified, where 1 indicates that a document was successfully modified.

6. db.<collection>.deleteOne()

Delete a document in the specified collection, for example:

```

db.users.deleteOne( { name: "John" } )

```

[Feedback information indicates: This is the return result of a MongoDB database operation. Among them, "acknowledged" indicates whether the operation is confirmed, if true, it indicates that the operation is confirmed; "deletedCount" indicates the number of deleted documents. So this return result indicates that a document was successfully deleted.

7. db.<collection>.count()

Returns the number of documents in the specified collection.

8. db.<collection>.drop()

 [Feedback information true indicates successful deletion]

Delete the specified collection.

9. db.createUser()

Create a new database user.

For example, if you want to create a user with a user name of `testuser`, a password of `testpassword`, a role of `readWrite`, and a database of `testdb`, you can use the following command:

```

db.createUser( { user: "testuser", pwd: "testpassword", roles: [ { role: "readWrite", db: "testdb" } ] } )

```

Note that `db.createUser()` can only be executed with administrator privileges. If you do not have administrator rights, you need to log in to MongoDB with an administrator account first, and then execute `db.createUser()`.

10. db.dropDatabase()

Delete the currently used database.

1. Open the MongoDB shell and connect to the database to be deleted.

2. Enter the `use <database_name>` command in the shell to switch to the database to be deleted.

3. Enter the `db.dropDatabase()` command to delete the currently connected database.

Note: This command will permanently delete the database and all its data, so use it with caution.

11. db.stats()

Get status information about the currently used database.

The above are common command operations and instructions for MongoDB, which can meet the needs of most daily work.

Configuration file description


The MongoDB configuration file is a text file used to specify the configuration information of MongoDB runtime. Starting MongoDB using a configuration file can make it more convenient to manage and configure MongoDB.

MongoDB's configuration file needs to be specified at startup, usually using the `mongod --config` command.

The following are common parameters of MongoDB configuration files and their descriptions:

- bindIp: The bound IP address. The default value is `0.0.0.0`, which means that all IP addresses can be connected. MongoDB access can be restricted by specifying a specific IP address or multiple IP addresses.

- port: The port MongoDB listens on. The default port number is 27017.

- dbpath: The folder path used by the MongoDB database. The default path is `/data/db`.

- logpath: The path to the MongoDB log file.

- logappend: If set to true, MongoDB's log files use append mode.

- quiet: If set to true, MongoDB does not output any log information.

- pidfilepath: MongoDB process ID file path.

- maxConns: The maximum number of connections allowed by MongoDB, the default value is `20000`.

- maxIncomingConnections: The maximum number of connections MongoDB allows to be opened at the same time. The default value is `65536`.

- storage: MongoDB storage engine, default is `wiredTiger`.

An example command to start MongoDB using a configuration file is as follows:

```

mongod --config /etc/mongod.conf

```

The above are the common parameters and descriptions of MongoDB configuration files. In practice, parameter values ​​need to be adjusted according to specific needs and hardware conditions to achieve optimal performance efficiency.

Backup operation


MongoDB has multiple backup methods, including hot backup and cold backup.

[When using cold and hot backup, try not to use them at the same time]

1. Hot backup

Hot backup is a way of backing up MongoDB while it is running. Specific steps are as follows:

(1) Use the mongodump command to export MongoDB backup data. The following command exports the backup data to the `/data/backup` directory:

```

mongodump --out /data/backup

```

(2) If you need to compress the exported backup data, you can use the following command:

```

tar -czvf backup.tar.gz /data/backup

```

2. Cold backup

Cold backup is a way to back up MongoDB when it is in a fresh startup state. Specific steps are as follows:

(1) Use MongoDB’s mongodump command to export MongoDB’s backup data. The following command exports the backup data to the `/data/backup` directory:

```

mongodump --out /data/backup

```

(2) Stop the MongoDB service:

```

sudo systemctl stop mongod

```

(3) Use the tar command to compress the funnel backup data into a file:

```

tar -czvf backup.tar.gz /data/backup

```

 Check

 vim opens backup.tar.gz

(4) Start the MongoDB service:

```

sudo systemctl start mongod

```

Backup is an important part of MongoDB management. Regular backup of MongoDB database is one of the important means to ensure data security. For production systems, an automated backup solution is recommended.

Restore operation


MongoDB uses the mongorestore command to restore backup data to MongoDB. The following are the steps to restore MongoDB backup data:

(1) Unzip the backup file

First, you need to unzip the MongoDB backup file. Assuming that the backup file `backup.tar.gz` is decompressed to the `/data/backup` directory, use the following command to decompress the backup file:

```

tar -xzvf backup.tar.gz -C /data/backup

```

(2) Stop the MongoDB service

During the restoration of backup data, the MongoDB service needs to be stopped to avoid surprises. Stop the MongoDB service using the following command:

```

sudo systemctl stop mongod

```

(3) Use the mongorestore command to restore backup data

Use the mongorestore command to restore backup data to MongoDB. The following command restores backup data to MongoDB:

```

mongorestore /data/backup

```

This command restores backup data to the original collection and database. You can also restore backup data to a new database by specifying the `--db` parameter.

(4) Restart the MongoDB service

After restoring the backup data, restart the MongoDB service:

```

sudo systemctl start mongod

```

The above are simple steps to restore MongoDB backup data. In practice, caution is required when backing up and restoring data to ensure data integrity and security.

MongoDB practical scenario application


You want to build an online retail store, which needs to process member data, order data, product data, etc. To save and manage this data, you can use MongoDB.

1. Design data schema

For data from an online retail store, you can design three MongoDB collections:

- Member information collection (Members): This collection contains basic information of members, such as name, email, address, purchase history, etc.

- Order information collection (Orders): This collection contains information about all orders, including order number, product name, unit price, quantity, shipping fee, etc.

- Product information collection (Products): This collection contains information about all sales products, such as name, description, price, inventory, etc.

You can use MongoDB's document format to store the data in each collection. For example, for a membership information collection, you could use the following document format:

```

{

   _id: ObjectId("5f096745c83ab13f9d887137"),

   name: "John Smith",

   email: "[email protected]",

   address: "123 Main St, Anytown USA",

   purchase_history: [

      {

         item: "Product A",

         date: ISODate("2022-01-01T10:00:00Z"),

         price: 99.99

      },

      {

         item: "Product B",

         date: ISODate("2022-01-05T14:30:00Z"),

         price: 49.99

      }

   ]

}

```

For order information collections and product information collections, you can use similar document formats to store data.

2. Insert data

Before you start running your online retail store, you need to insert some test data into MongoDB. You can use MongoDB's insertMany command to batch insert data sets:

mongo shell Log in to mongdb and type the following command into the command line

```

db.members.insertMany([

   {

      name: "John Smith",

      email: "[email protected]",

      address: "123 Main St, Anytown USA",

      purchase_history: [

         {

            item: "Product A",

            date: ISODate("2022-01-01T10:00:00Z"),

            price: 99.99

         },

         {

            item: "Product B",

            date: ISODate("2022-01-05T14:30:00Z"),

            price: 49.99

         }

      ]

   },

   {

      name: "Jane Doe",

      email: "[email protected]",

      address: "456 Oak St, Another Town USA",

      purchase_history: [

         {

            item: "Product C",

            date: ISODate("2022-01-10T09:45:00Z"),

            price: 149.99

         },

         {

            item: "Product A",

            date: ISODate("2022-01-15T11:30:00Z"),

            price: 99.99

         }

      ]

   }

]);

db.orders.insertMany([

   {

      order_number: "1001",

      product_name: "Product A",

      price: 99.99,

      quantity: 2,

      shipping: 5.99,

      order_date: ISODate("2022-01-01T10:00:00Z")

   },

   {

      order_number: "1002",

      product_name: "Product B",

      price: 49.99,

      quantity: 3,

      shipping: 7.99,

      order_date: ISODate("2022-01-05T14:30:00Z")

   }

]);

db.products.insertMany([

   {

      name: "Product A",

      description: "A great product!",

      price: 99.99,

      stock: 100

   },

   {

      name: "Product B",

      description: "Another great product!",

      price: 49.99,

      stock: 50

   },

   {

      name: "Product C",

      description: "The greatest product of all!",

      price: 149.99,

      stock: 25

   }

]);

```

 

3. Query data

Suppose you want to display the purchase history of a certain member in your online retail store, you can use the following query to retrieve the data:

Use the command to view

```

db.members.find({ name: "John Smith"})

 

Guess you like

Origin blog.csdn.net/2302_77750172/article/details/131185161