介绍安装、远程连接以及基本操作。

环境:CentOS7-1708
MongoDB:3.4.9

安装并设置为开机启动

看官网教程,很详细,按照文档操作即可

安装过程,简单记录如下

  1. 添加 yum 源

    1
    2
    3
    4
    5
    6
    7
    8
    9
    cd /etc/yum.repos.d/
    vim /etc/yum.repos.d/mongodb-org-3.4.repo
    # 添加如下内容
    [mongodb-org-3.4]
    name=MongoDB Repository
    baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
    gpgcheck=1
    enabled=1
    gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
  2. 添加 yum 源后,通过 yum 安装

    1
    yum install -y mongodb-org
  3. Disable SELinux by setting the SELINUX setting to disabled in /etc/selinux/config

    1
    2
    3
    vi /etc/selinux/config
    # 将原来的注释掉,添加:
    SELINUX=disabled
  4. 设置为开机启动

    1
    2
    chkconfig mongod on
    # 或者 systemctl enable mongod.service
  5. 重启,检测是否已经启动

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    [root@192 ~]# service mongod status
    Redirecting to /bin/systemctl status mongod.service
    ● mongod.service - High-performance, schema-free document-oriented database
    Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
    Active: active (running) since Thu 2017-10-05 21:59:36 HKT; 2min 7s ago
    Docs: https://docs.mongodb.org/manual
    Process: 1436 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
    Process: 1426 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
    Process: 1415 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
    Main PID: 1702 (mongod)
    CGroup: /system.slice/mongod.service
    └─1702 /usr/bin/mongod -f /etc/mongod.conf

    Oct 05 21:59:35 192.168.1.18 systemd[1]: Starting High-performance, schema-free document-oriented database...
    Oct 05 21:59:36 192.168.1.18 systemd[1]: Started High-performance, schema-free document-oriented database.
    Oct 05 21:59:47 192.168.1.18 mongod[1443]: about to fork child process, waiting until server is ready for connections.
    Oct 05 21:59:47 192.168.1.18 mongod[1443]: forked process: 1702
  6. 查看日志

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    [root@192 ~]# cd /var/log/mongodb/
    [root@192 mongodb]# tail -f mongod.log
    2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten]
    2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
    2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
    2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten]
    2017-10-05T21:59:50.635+0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/var/lib/mongo/diagnostic.data'
    2017-10-05T21:59:50.784+0800 I INDEX [initandlisten] build index on: admin.system.version properties: { v: 2, key: { version: 1 }, name: "incompatible_with_version_32", ns: "admin.system.version" }
    2017-10-05T21:59:50.784+0800 I INDEX [initandlisten] building index using bulk method; build may temporarily use up to 500 megabytes of RAM
    2017-10-05T21:59:50.788+0800 I INDEX [initandlisten] build index done. scanned 0 total records. 0 secs
    2017-10-05T21:59:50.789+0800 I COMMAND [initandlisten] setting featureCompatibilityVersion to 3.4
    2017-10-05T21:59:50.790+0800 I NETWORK [thread1] waiting for connections on port 27017
  7. 注意事项。

  • The MongoDB instance stores its data files in /var/lib/mongo and its log files in /var/log/mongodb by default, and runs using the mongod user account. You can specify alternate log and data file directories in /etc/mongod.conf. See systemLog.path and storage.dbPath for additional information.
  • If you change the user that runs the MongoDB process, you must modify the access control rights to the /var/lib/mongo and /var/log/mongodb directories to give this user access to these directories.

实现远程连接

  1. 修改配置

    1
    2
    3
    4
    5
    6
    7
    vi /etc/mongod.conf
    # 注释掉下面这行,备注也有说明。
    # bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.
    # 将 #security:中的#去掉,并在其下加一行,空两个空格,加上authorization: enabled,如下
    security:
    authorization: enabled
    # 注意:authorization: enabled中冒号后加一个空格,这是 yaml 语法格式
  2. 防火墙开放 27017 端口
    CentOS 7中防火墙是一个非常的强大的功能,在CentOS 6.5中在iptables防火墙中进行了升级了。名字也变了,叫:firewall

    1
    2
    3
    4
    5
    [root@192 ~]# firewall-cmd --permanent --add-port=27017/tcp
    success
    [root@192 ~]# firewall-cmd --reload
    success
    [root@192 ~]# systemctl restart firewalld.service
  3. 参数含义

  • firwall-cmd:是Linux提供的操作firewall的一个工具;
  • –permanent:表示设置为持久;
  • –add-port:标识添加的端口;
  • –zone=public:指定的 zone 为 public;上面的参数没用这个,zone 默认为 public

如果 –zone=dmz 这样设置的话,会在 dmz.xml 文件中新增一条。

执行上面的命令之后,被修改的配置文件为: /etc/firewalld/zones/public.xml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<zone>
<short>Public</short>
<description>For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
<service name="ssh"/>
<service name="dhcpv6-client"/>
<port protocol="tcp" port="27017"/>
</zone>

其中最后一行就是新添加进去的。

附 firewall常用命令

firewall常用命令 功能
service firewalld restart 重启
service firewalld start 开启
service firewalld stop 关闭
systemctl status firewall 或 firewall-cmd –state 查看firewall服务状态
firewall-cmd –list-all 查看防火墙规则
systemctl disable firewalld.service 禁止firewall开机启动
  • firewall常用命令,测试
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    [root@192 zones]# firewall-cmd --state
    running
    [root@192 zones]# systemctl status firewalld.service
    ● firewalld.service - firewalld - dynamic firewall daemon
    Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
    Active: active (running) since Thu 2017-10-05 23:49:12 HKT; 13s ago
    Docs: man:firewalld(1)
    Main PID: 4325 (firewalld)
    CGroup: /system.slice/firewalld.service
    └─4325 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --destination 192.168.122.0/24 --out-interface virbr0 --match conntrack --ctstate ESTABLISHED,RELATED --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --source 192.168.122.0/24 --in-interface virbr0 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --in-interface virbr0 --out-interface virbr0 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --out-interface virbr0 --jump REJECT' failed: iptables: No chain/target/match by that name.
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --in-interface virbr0 --jump REJECT' failed: iptables: No chain/target/match by that name.
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol udp --destination-port 53 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol tcp --destination-port 53 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete OUTPUT --out-interface virbr0 --protocol udp --destination-port 68 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol udp --destination-port 67 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).
    Oct 05 23:49:13 192.168.1.18 firewalld[4325]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol tcp --destination-port 67 --jump ACCEPT' failed: iptables: Bad rule (does a matching rule exist in that chain?).

    [root@192 zones]# firewall-cmd --list-all
    public (active)
    target: default
    icmp-block-inversion: no
    interfaces: enp0s3
    sources:
    services: ssh dhcpv6-client
    ports: 27017/tcp
    protocols:
    masquerade: no
    forward-ports:
    source-ports:
    icmp-blocks:
    rich rules:

添加管理员账户

启动 Mongo shell,并依次执行命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
[root@192 ~]# mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
2017-10-05T21:59:50.254+0800 I CONTROL [initandlisten]
2017-10-05T21:59:50.254+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-10-05T21:59:50.254+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-10-05T21:59:50.254+0800 I CONTROL [initandlisten]
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten]
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten]
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-10-05T21:59:50.255+0800 I CONTROL [initandlisten]
> show dbs;
admin 0.000GB
local 0.000GB
> use admin;
switched to db admin
> db.createUser(
{
user: "mongoRoot",
pwd: "mongoRootPassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)

Successfully added user: {
"user" : "mongoRoot",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> exit;

重启 mongodb 数据库

1
2
3
[root@192 ~]# service mongod restart
Redirecting to /bin/systemctl restart mongod.service
[root@192 ~]#

service 是 CentOS 7 以前的命令,新的命令是 systemctl,旧命令还能执行,应该是为了兼容,或者说是照顾 CentOS7 以前的用户。

1
2
[root@192 ~]# systemctl restart mongod.service
[root@192 ~]#

开启认证之后,再用 mongo 进入 mongo shell,需要先认证才能执行管理命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@192 ~]# mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
> show dbs;
2017-10-06T00:13:40.276+0800 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:769:19
shellHelper@src/mongo/shell/utils.js:659:15
@(shellhelp2):1:1
> use admin
switched to db admin
> db.auth("mongoRoot", "mongoRootPassword")
1
> show dbs
admin 0.000GB
local 0.000GB
>

创建数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
> use myDB
switched to db myDB
> db.createUser(
{
user: "myDBRoot",
pwd: "myDBRootPassword",
roles: [ { role: "dbAdmin", db: "myDB" } ]
}
)
Successfully added user: {
"user" : "myDBRoot",
"roles" : [
{
"role" : "dbAdmin",
"db" : "myDB"
}
]
}
> db.auth("myDBRoot", "myDBRootPassword")
1
> db.createCollection(myDBCollection)
2017-10-06T00:43:44.050+0800 E QUERY [thread1] ReferenceError: myDBCollection is not defined :
@(shell):1:1
> db.createCollection("myDBCollection")
{ "ok" : 1 }
>

创建超级管理员及普通的用户,修改用户密码。注意一点,帐号是跟着库走的,所以在指定库里授权,必须也在指定库里验证(auth)。

常用角色

角色 角色说明
Read 允许用户读取指定数据库。
readWrite 允许用户读写指定数据库。
dbAdmin 允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile。
userAdmin 允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户。
clusterAdmin 只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
readAnyDatabase 只在admin数据库中可用,赋予用户所有数据库的读权限。
readWriteAnyDatabase 只在admin数据库中可用,赋予用户所有数据库的读写权限。
userAdminAnyDatabase 只在admin数据库中可用,赋予用户所有数据库的userAdmin权限。
dbAdminAnyDatabase 只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
root 只在admin数据库中可用。超级账号,超级权限。

IDEA 插件方式连接 MongoDB

超时才返回错误信息

认证方式没有选最后一项,即:SCRAM-SHA-1,报错,前面两项都报错,而且需要超时才报错。

1
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.1.18:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=PLAIN, userName='myDBRoot', source='myDB', password=<hidden>, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 2: 'Unsupported mechanism PLAIN' on server 192.168.1.18:27017. The full response is { "supportedMechanisms" : ["MONGODB-CR", "MONGODB-X509", "SCRAM-SHA-1"], "ok" : 0.0, "errmsg" : "Unsupported mechanism PLAIN", "code" : 2, "codeName" : "BadValue" }}}]

立即返回错误信息

认证方式选:SCRAM-SHA-1,如果用户名输入错误,会立即,注意,是立即返回错误信息。

1
com.mongodb.MongoCommandException: Command failed with error 13: 'not authorized on myDBmyDB to execute command { listCollections: 1, cursor: { batchSize: 0 } }' on server 192.168.1.18:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on myDBmyDB to execute command { listCollections: 1, cursor: { batchSize: 0 } }", "code" : 13, "codeName" : "Unauthorized" }