MongoDB安装

注意
本文最后更新于 2023-12-13,文中内容可能已过时。

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

Community Server

Package用途
mogosMongoDB shard缩写,分片使用
server通过包管理工具安装
shellMongoDB shell
tgz二进制包
Source源码包

下载地址

1
2
3
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu2004-5.0.9.tgz
tar -zxf mongodb-linux-x86_64-ubuntu2004-5.0.9.tgz
mv mongodb-linux-x86_64-ubuntu2004-5.0.9 /usr/local/mongodb

创建日志目录和数据文件目录

1
2
mkdir -p /usr/local/mongodb/data/{logs,db}
touch data/logs/mongodb.log
1
2
3
4
5
#set mysql environment
export MONGO_HOME=/usr/local/mongodb
export PATH=${PATH}:${MONGO_HOME}/bin

source /etc/profile

启动 MongoDB 有2种方式,一是直接指定配置参数,二是指定配置文件。

创建一个文件mongod.conf,填写下列项:

 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
46
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
   destination: file #日志输出方式。file/syslog,如果是file,需指定path,默认是输出到标准输出流中
   logAppend: true #启动时,日志追加在已有日志文件还是创建新文件记录日志, 默认false
   logRotate: reopen #rename 重命名日志文件。reopen 按照Linux/Unix日志滚动行为关闭和重新打开日志文件。必须设置logAppend为true
   path: /usr/local/mongodb/data/logs/mongod.log #日志路径。

# Where and how to store data.
storage:
   dbPath: /usr/local/mongodb/data/db #数据目录
   journal: #64位系统默认打开,32位关闭
      enabled: true
#  engine:
#  wiredTiger:

# how the process runs
processManagement:
   fork: true  # fork and run in background
   pidFilePath: /usr/local/mongodb/mongod.pid  # location of pidfile
   timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
   port: 27017
   bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
   maxIncomingConnections: 65536 #最大连接数,默认65536

security:
   authorization: enabled # enabled/disabled 开启客户端认证

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:

官方说明Configuration File Options

启动mongo

1
mongod --config /usr/local/mongodb/mongod.conf

关闭mongo

1
mongod --shutdown --config /usr/local/mongodb/mongod.conf
1
mongo --port=27017

这里说明一下,如果是27017默认端口号,则不需要指定,直接./mongo就可以进入交互控制台,如果配置文件的端口不是默认端口,启动终端要指定端口号。

接着你输入show dbs,就会看到以下默认集合:

1
2
3
4
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

https://img.bwcxtech.com/img/202207071109724.png

官方文档

MongoDB 默认是没有开启安全认证的,对于部署在云上就显得及其不安全,下面我们为mongodb的admin数据库创建用户。

MongoDB数据库有以下特点:

  • 没有默认管理员账号,所以要先添加管理员账号,在开启权限认证。
  • 切换到admin数据库,添加的账号才是管理员账号。
  • 用户只能在用户所在数据库登录,包括管理员账号。
  • 管理员可以管理所有数据库,但是不能直接管理其他数据库,要先在admin数据库认证后才可以。这一点比较特别。

在admin数据库中添加具有userAdminAnyDatabase角色的用户

使用db.createUser()函数在admin数据库下创建用户,老版本的MongodDB是db.addUser()函数

1
2
3
4
5
6
> use admin
> db.createUser({
    user:"admin",
    pwd:"123456",
    roles:["root"]
}) //创建超级管理员

https://img.bwcxtech.com/img/202207071404397.png

userAdminAnyDatabase:授予在所有数据库上管理User的权限-意思是可以在所有的数据库管理User,但是没有操作权利,只有你在那个数据库验证了User,然后才能去操作数据库的读写。

现在我们成功的创建了用户和密码,将mongodb.conf文件中的开启安全认证项修改为 true

1
2
security:
   authorization: enabled

重启mongo

1
2
mongod --shutdown --config /usr/local/mongodb/mongodb.conf
mongod --config /usr/local/mongodb/mongodb.conf

验证

1
mongo --port=27017
1
2
3
4
5
6
7
8
> use admin
> db.createUser(
  {
    user: "test",
    pwd: "test",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

https://img.bwcxtech.com/img/202207071411278.png

我们可以看到结果显示失败未验证,说明我们刚才开启MongoDB密码登录成功。

下面我们需要验证,首先切换到admin数据库下,也就是说,验证步骤必须在admin数据库下面进行

1
2
3
4
> use admin
> db.auth("root","root")

1

db.auth()函数是验证方法,可以看到显示结果1表示成功验证,这个时候我们再show dbs,就成功显示了。 这个时候我们就可以对数据库任意操作了。

https://img.bwcxtech.com/img/202207071413565.png

先关闭服务

1
mongod --shutdown --config /usr/local/mongodb/mongodb.conf

配置服务,使用systemctl管理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
cat > /usr/lib/systemd/system/mongodb.service <<'EOF'
[Unit]
Description=MongoDB Service
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/mongodb/bin/mongod --config /usr/local/mongodb/mongodb.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/usr/local/mongodb/bin/mongod --shutdown --config /usr/local/mongodb/mongodb.conf
PrivateTmp=true

[Install] 
WantedBy=multi-user.target
EOF

启动服务

1
systemctl enable mongodb.service --now

官方文档

数据库用户角色:read、readWrite;

数据库管理角色:dbAdmin、dbOwner、userAdmin;

集群管理角色: clusterAdmin、clusterManager、clusterMonitor、hostManager;

备份恢复角色: backup、restore;

所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase

超级用户角色: root; 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)

内部角色: __system;

-—————————————————————————————–

角色说明:

Read: 允许用户读取指定数据库

readWrite: 允许用户读写指定数据库

dbAdmin: 允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile

userAdmin: 允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户

dbOwner: 允许在当前DB中执行任意操作

readAnyDatabase: 赋予用户所有数据库的读权限,只在admin数据库中可用

readWriteAnyDatabase: 赋予用户所有数据库的读写权限,只在admin数据库中可用

userAdminAnyDatabase:赋予用户所有数据库管理User的权限,只在admin数据库中可用

dbAdminAnyDatabase: 赋予管理所有数据库的权限,只在admin数据库中可用

root: 超级账号,超级权限,只在admin数据库中可用。

-—————————————————————————————–

集群管理角色:

clusterAdmin: 赋予管理集群的最高权限,只在admin数据库中可用

clusterManager: 赋予管理和监控集群的权限

clusterMonitor: 赋予监控集群的权限,对监控工具具有readonly的权限

hostManager: 赋予管理Server

1
2
db.createUser({user:"test",pwd:"test",roles:[ {role:"read", db:"test" }]})
db.createUser({user:"test",pwd:"test",roles:[ {role:"readAnyDatabase",db:"admin" }, {role:"readWrite",db:"test" } ]})
1
db.dropUser('test')
1
db.updateUser("test",{roles:[ {role:"readWrite",db:"test"} ]})

从MongoDB 4.4开始,MongoDB现在与MongoDB服务器分开发布,并使用自己的版本控制,初始版本为100.0.0。在此之前,MongoDB与MongoDB服务器一起发布

下载地址

1
mongodump -h <hostname><:port> -u 用户名 -p 密码 -d dbname -o dbdirectory

出现 Authentication failed

添加--authenticationDatabase admin选项

1
mongodump -h -u -p --port 27017 --authenticationDatabase admin -o /tmp/backup
1
mongodump -h -u admin -p 123456 --port 27017 --authenticationDatabase admin -d test -o test
1
2
3
4
5
# 压缩备份单库
mongodump -h -u -p --port 27017 --authenticationDatabase admin -d test -o /tmp/backup --gzip

# 压缩备份单表
mongodump -h -u -p --port 27017 --authenticationDatabase admin -d test -c customer -o /tmp/backup --gzip
1
mongorestore -h <hostname><:port> -d dbname <path>
1
mongorestore -h -u -p --port 27017 --authenticationDatabase admin -d test /tmp/backup/test
1
mongorestore -h -u -p --port 27017 --authenticationDatabase admin -d test -c customer /tmp/back
1
2
mongorestore -h -u -p --port 27017 --authenticationDatabase admin --gzip /tmp/backup
mongorestore -h 127.0.0.1 -u admin -p 123456 --port 27017 --authenticationDatabase admin -d test --gzip test

2022-07-07T16:01:44.751+0800 The –db and –collection flags are deprecated for this use-case; please use –nsInclude instead, i.e. with –nsInclude=${DATABASE}.${COLLECTION} 2022-07-07T16:01:44.751+0800 building a list of collections to restore from test dir 2022-07-07T16:01:44.751+0800 don’t know what to do with subdirectory “test/test”, skipping… 2022-07-07T16:01:44.752+0800 0 document(s) restored successfully. 0 document(s) failed to restore.

没有任何报错,但是也没有恢复任何数据。

1
mongorestore -u admin -p 123456 --port 27017 --authenticationDatabase admin --nsInclude="*" test

https://img.bwcxtech.com/img/202207071605151.png

可以看到恢复1个document

mongo不支持跨版本升级

升级过程4.2.3→4.4→5.0→6.0.2

查看当前功能兼容性版本

1
db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )

设置功能兼容性版本

1
2
3
db.adminCommand( { setFeatureCompatibilityVersion: "4.4" } )
db.adminCommand( { setFeatureCompatibilityVersion: "5.0" } )
db.adminCommand( { setFeatureCompatibilityVersion: "6.0" } )

参考链接:

Upgrade a Replica Set to 5.0

Upgrade a Replica Set to 6.0

相关内容