How to install MongoDB on Ubuntu?

1. Install MongoDB on Ubuntu

MongoDB installation is very simple. There is no need to download the source files. You can install it directly with the apt-get command. Open the terminal and enter the following command

sudo apt-get install mongodb

After this is installed, the mongod program should automatically run. Use the command to check whether the process has started.

pgrep mongo -l

command window results

root@iZm5eetszs07500os8erolZ:~# pgrep mongo -l
32216 mongod
root@iZm5eetszs07500os8erolZ:~#

2. Shut down/start MongoDB

Shut down MongoDB

sudo service mongodb stop 

Start MongoDB

sudo service mongodb start

3. Systemd manages MongoDB

Check service status

sudo systemctl status mongodb

command window results

Other commands

// 状态查询
sudo systemctl status mongodb

//停用
sudo systemctl stop mongodb

//启动
sudo systemctl start mongodb

//重启
sudo systemctl restart mongodb

Modify whether MongoDB automatically starts with the system (default: enabled)

sudo systemctl disable mongodb

sudo systemctl enable mongodb

Note: It is highly not recommended to use kill to forcefully kill the process, as this may cause data corruption.

4. Uninstall MongoDB

If you installed MongoDB from the Ubuntu repository and want to uninstall it (possibly using an officially supported method), you can type:

sudo systemctl stop mongodb

sudo apt purge mongodb

sudo apt autoremove

5. Catalog description

By default, the package manager will create /var/lib/mongodbthe and /var/log/mongodbconfiguration file directories as/etc/mongodb.conf

6. Using MongoDB

6.1 Using database

In MongoDB, each database instance can have multiple users. After the security check is turned on, only authenticated users can read and write data. Admin (administrator) and local (local) are two special databases, and users in them can operate any database. Users in these two databases can be considered superusers. After authentication, administrator users can read and write to any database, and can also execute certain commands that only administrators can execute, such as listDatabases and shutDown.

By default, mongod listens on 127.0.0.1, and any client can connect directly to 27017 without authentication. The advantage of this is that users can get started immediately without worrying about being upset by a bunch of configurations. However, the disadvantages are also obvious. If MongoDB is built directly on the public server, everyone can directly access and modify the database data.

MongoDB does not set authentication by default, and most projects using MongoDB in the industry do not set access permissions. This means that as long as the port of the MongoDB server is known, anyone with access to the server can query and operate the contents of the MongoDB database. In some projects, this usage will be regarded as a security vulnerability.

In fact, MongoDB itself has very detailed security configuration guidelines. Obviously the developer has thought of it. However, he pushed the security task to the users to solve. This strategy itself is biased towards ease of use and has to stand aside for security. .

Note: Each database has its own user. The command to create a user is db.createUser(). When you create a user, the user belongs to the database you are currently in.

One of the strange settings of MongoDB is that even for an admin user, authorization must be performed under the admin database and not under other databases. After authorization, the admin user can perform any operation in any database. Of course, database-level users cannot operate in other databases after being authorized under their own database.

Standard URI connection syntax:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
 
mongodb:// 这是固定的格式,必须要指定。
username:password@ 可选项,如果设置,在连接数据库服务器之后,驱动都会尝试登陆这个数据库
host1 必须的指定至少一个host, host1 是这个URI唯一要填写的。它指定了要连接服务器的地址。如果要连接复制集,请指定多个主机地址。
portX 可选的指定端口,如果不填,默认为27017
/database 如果指定username:password@,连接并验证登陆指定数据库。若不指定,默认打开admin数据库。
?options 是连接选项。如果不使用/database,则前面需要加上/。所有连接选项都是键值对name=value,键值对之间通过&或;(分号)隔开

root@iZm5eetszs07500os8erolZ:~# mongo mongodb://127.0.0.1:27017
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Server has startup warnings:
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten]
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten]
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten]
> show databases;
admin   0.000GB
config  0.000GB
local   0.000GB
>

Connect using shell:

root@iZm5eetszs07500os8erolZ:~# mongo
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Server has startup warnings:
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten]
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten]
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten]
> show databases;
admin   0.000GB
config  0.000GB
local   0.000GB
> use admin
switched to db admin
>

Command description

//进入数据库
mongo

//显示数据库
show databases;

//使用数据库
use admin

6.2 Create user

First make sure you have logged in to the admin database as a user administrator. Then use the use command to switch to the target database, and also use the db.createUser() command to create a user. The role name is "readWrite". There are two common database user roles, read and readWrite. As the name suggests, the former can only read data but cannot modify it, while the latter can read and modify it.

root@iZm5eetszs07500os8erolZ:~# mongo
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Server has startup warnings:
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten]
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2021-07-26T16:03:25.186+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten]
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2021-07-26T16:03:26.300+0800 I CONTROL  [initandlisten]
> use admin
switched to db admin
> db.createUser({user:"root",pwd:"root123abc",roles:["userAdminAnyDatabase"]})
Successfully added user: { "user" : "root", "roles" : [ "userAdminAnyDatabase" ] }
> use admin
switched to db admin
> db.auth("root","root123abc")
1
> show users;
{
        "_id" : "admin.root",
        "user" : "root",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
>

Command description

//创建root用户
db.createUser({user:"root",pwd:"root123abc",roles:["userAdminAnyDatabase"]})

//root登录 db.auth()方法返回1表示登录成功。
db.auth("root","root123abc")

//查看用户
show users;

6.3 Delete users

>db.system.users.remove({"user" : "test_user"});  删除一个test_user用户

6.4 Use of mongodb create, delete, and insert data commands

root@iZm5eetszs07500os8erolZ:~# mongo  
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Server has startup warnings:
2021-07-26T17:22:22.563+0800 I STORAGE  [initandlisten]
2021-07-26T17:22:22.563+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2021-07-26T17:22:22.563+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2021-07-26T17:22:23.721+0800 I CONTROL  [initandlisten]
2021-07-26T17:22:23.721+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-07-26T17:22:23.721+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2021-07-26T17:22:23.721+0800 I CONTROL  [initandlisten]
> use test     #创建一个test数据库
switched to db test
> show dbs;    #列出所有数据库
admin   0.000GB
config  0.000GB
local   0.000GB

# 但是并没有看到刚才我们创建的test数据库,那是因为test数据库是空的,我们插入一条数据

> db.test.insert({"name":"alanchen"})
WriteResult({ "nInserted" : 1 })
> db.test.find({"name":"alanchen"})     #查询数据
{ "_id" : ObjectId("60fe80e2098d05fbdf907486"), "name" : "alanchen" }
> db.test.findOne()    #查询一条数据
{ "_id" : ObjectId("60fe80e2098d05fbdf907486"), "name" : "alanchen" }

> show dbs;    #test 数据库就显示了
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

> db.dropDatabase();   # 删除数据库
{ "dropped" : "test", "ok" : 1 }

> show dbs;  # test数据库不显示了
admin   0.000GB
config  0.000GB
local   0.000GB
>

7. MongoDB storage engine

The Storage Engine is the core component of MongoDB and is responsible for managing how data is stored on the hard disk (Disk) and memory (Memory). Starting from MongoDB version 3.2, MongoDB supports multiple data storage engines (Storage Engine). The storage engines supported by MongoDB are: WiredTiger, MMAPv1 and In-Memory.

Starting from MongoDB version 3.2, WiredTiger becomes the default Storage Engine of MongoDB, which is used to persist data into hard disk files. WiredTiger provides document-level concurrency control, checkpoint (CheckPoint), data compression and local data. Encryption (Native Encryption) and other functions.
MongoDB can not only store data persistently in hard disk files, but also save data only in memory; the In-Memory storage engine is used to store data only in memory, with only a small amount of metadata and diagnostic logs (Diagnostic logs). ) is stored in the hard disk file. Since the requested data can be obtained without the need for Disk IO operations, the In-Memory storage engine greatly reduces the latency of data query (Latency).

View MongoDB’s default storage engine:

echo "db.serverStatus()"| mongo|grep wiredTiger

command window results

root@iZm5eetszs07500os8erolZ:~# echo "db.serverStatus()"| mongo|grep wiredTiger
                "name" : "wiredTiger",
        "wiredTiger" : {
root@iZm5eetszs07500os8erolZ:~#

Both WiredTiger and MMAPv1 are used to persistently store data. Relatively speaking, WiredTiger is newer and more powerful than MMAPv1.

8. Precautions for using MongoDB and performance optimization

  • Test every query in your application using explain()
  • Avoid scatter-gather queries
  • Your operational application should only read from the master node
  • Use the latest driver for MongoDB
  • Store all recorded data in a single document
  • Avoid large documents
  • Avoid using large indexed arrays
  • Avoid unnecessarily long field names
  • Use caution when considering indexes on low cardinality fields
  • Cancel unnecessary indexes
  • Drop an index that is a prefix of another index
  • Use composite indexes instead of index intersections
  • Avoid regular expressions that do not leave anchoring or rooting
  • Use the index optimization provided in the WiredTiger storage engine (the default is the WiredTiger engine after version 3.0)
  • Use multiple devices with different databases - WiredTiger
  • Avoid using ext3 file system, use ext4 or xfs file system

Guess you like

Origin blog.csdn.net/quanzhan_King/article/details/131260151