MongoDB概述与部署(二)

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
简介: MongoDB概述与部署(二)

二、部署MongoDB


(1)实验环境


系统 ip 主机名 MongoDB版本
Centos7.4 192.168.100.202 mongodb mongodb-linux-x86_64-rhel70-4.4.5.tgz mongodb-database-tools-rhel70-x86_64-100.3.1.tgz


(2)实验步骤


******(1)先做基础配置
[root@Centos7 ~]# hostnamectl set-hostname mongodb
[root@Centos7 ~]# su
[root@mongodb ~]# systemctl stop firewalld
[root@mongodb ~]# setenforce 0
setenforce: SELinux is disabled
[root@mongodb ~]# mount /dev/cdrom /mnt/
mount: /dev/sr0 写保护,将以只读方式挂载
mount: /dev/sr0 已经挂载或 /mnt 忙
       /dev/sr0 已经挂载到 /mnt 上
******(2)上传源码包,MongoDB 4版本以上的/bin目录中的工具进行了分离,只有一些基础工具可以使用,需要安装插件才能使用/bin下的其他工具
[root@mongodb ~]# ll
总用量 133084
-rw-------. 1 root root     1264 1月  12 18:27 anaconda-ks.cfg
-rw-r--r--  1 root root 64213416 6月  11 18:28 mongodb-database-tools-rhel70-x86_64-100.3.1.tgz  #这个就是工具包
-rw-r--r--  1 root root 72053873 6月  11 18:15 mongodb-linux-x86_64-rhel70-4.4.5.tgz
[root@mongodb ~]# ulimit -n 25000  #同一时间最多开启的文件数
[root@mongodb ~]# ulimit -u 25000  #用户最多开启的程序数目
[root@mongodb ~]# echo 0 > /proc/sys/vm/zone_reclaim_mode  #设置内核参数,表示当某个节点内存不足时,可以借用其他节点的内存 
[root@mongodb ~]# sysctl -w vm.zone_reclaim_mode=0
vm.zone_reclaim_mode = 0
[root@mongodb ~]# echo never >/sys/kernel/mm/transparent_hugepage/enabled
[root@mongodb ~]# echo never >/sys/kernel/mm/transparent_hugepage/defrag
[root@mongodb ~]# tar xf mongodb-linux-x86_64-rhel70-4.4.5.tgz 
[root@mongodb ~]# mkdir /usr/local/mongodb
[root@mongodb ~]# mv  mongodb-linux-x86_64-rhel70-4.4.5 /usr/local/mongodb/
[root@mongodb ~]# echo "export PATH=/usr/local/mongodb/bin:\$PATH" >>/etc/profile  #修改环境变量优化MongoDB命令执行路径
[root@mongodb ~]# source /etc/profile
[root@mongodb ~]# tar xf mongodb-database-tools-rhel70-x86_64-100.3.1.tgz 
[root@mongodb ~]# mkdir /usr/local/mongodb/bin
[root@mongodb ~]# mv mongodb-database-tools-rhel70-x86_64-100.3.1/bin/* /usr/local/mongodb/bin/
[root@mongodb ~]# ln -s /usr/local/mongodb/mongodb-linux-x86_64-rhel70-4.4.5/bin/* /usr/local/mongodb/bin/
******(3)创建mongodb的存储目录以及配置文件
[root@mongodb ~]# mkdir /usr/local/mongodb/data
[root@mongodb ~]# mkdir /usr/local/mongodb/logs
[root@mongodb ~]# mkdir /usr/local/mongodb/conf
[root@mongodb ~]# touch /usr/local/mongodb/logs/mongodb.log
[root@mongodb ~]# chmod 777 /usr/local/mongodb/logs/mongodb.log 
[root@mongodb ~]# vim /usr/local/mongodb/conf/mongodb.conf
bind_ip=192.168.100.202  #指定ip
port=27017   #指定端口
dbpath=/usr/local/mongodb/data/ #指定数据存储路径
logpath=/usr/local/mongodb/logs/mongodb.log  #指定日志存储路径
logappend=true   #mongodb日志以追加的方式写入
fork=true    #启动的时候,将mongodb放后台启动
maxConns=5000    #mongodb最大的连接数
******(4)编写服务启动脚本
[root@mongodb ~]# mongod -f /usr/local/mongodb/conf/mongodb.conf  #启动mongodb
about to fork child process, waiting until server is ready for connections.
forked process: 1181
child process started successfully, parent exiting
[root@mongodb ~]# netstat -anpt | grep mongo  #查看是否成功启动
tcp        0      0 192.168.100.202:27017   0.0.0.0:*               LISTEN      1181/mongod  
[root@mongodb ~]# mongo --port 27017 --host 192.168.100.202  #登录mongodb
MongoDB shell version v4.4.5
connecting to: mongodb://192.168.100.202:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("884dbe0a-4ef6-4118-9599-fc3c2118170c") }
MongoDB server version: 4.4.5
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
  https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
  https://community.mongodb.com
---
The server generated these startup warnings when booting: 
        2021-06-11T18:32:24.504+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2021-06-11T18:32:24.504+08:00: You are running this process as the root user, which is not recommended
        2021-06-11T18:32:24.504+08:00: Soft rlimits too low
        2021-06-11T18:32:24.504+08:00:         currentValue: 25000
        2021-06-11T18:32:24.504+08:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).
        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.
        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> exit
bye
[root@mongodb ~]# mongod -f /usr/local/mongodb/conf/mongodb.conf --shutdown #关闭mongodb
killing process with pid: 1181
[root@mongodb ~]# netstat -anpt | grep mongo
[root@mongodb ~]# echo /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb.conf>>/etc/rc.local   #添加mongodb开机自启
[root@mongodb ~]# vim /etc/init.d/mongodb
#!/bin/bash
case "$1" in
'start')
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb.conf;;
'stop')
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb.conf --shutdown;;
'restart')
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb.conf --shutdown
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/bin/mongodb.conf;;
esac
#保存退出
[root@mongodb ~]# chmod +x /etc/init.d/mongodb  #添加可执行权限
[root@mongodb ~]# /etc/init.d/mongodb start   #启动
about to fork child process, waiting until server is ready for connections.
forked process: 1234
child process started successfully, parent exiting
[root@mongodb ~]# netstat -anpt | grep mongo
tcp        0      0 192.168.100.202:27017   0.0.0.0:*               LISTEN      1234/mongod         
[root@mongodb ~]# /etc/init.d/mongodb stop   #关闭
killing process with pid: 1234
[root@mongodb ~]# netstat -anpt | grep mongo
******(5)测试访问mongodb数据库
[root@mongodb ~]# /etc/init.d/mongodb start 
about to fork child process, waiting until server is ready for connections.
forked process: 1291
child process started successfully, parent exiting
[root@mongodb ~]# mongo --port 27017 --host 192.168.100.202  #或者mongo 192.168.100.202:27017也可以
MongoDB shell version v4.4.5
connecting to: mongodb://192.168.100.202:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a872ecf6-4081-47b6-9559-dccb674f144a") }
MongoDB server version: 4.4.5
---
The server generated these startup warnings when booting: 
        2021-06-11T18:38:54.222+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2021-06-11T18:38:54.222+08:00: You are running this process as the root user, which is not recommended
        2021-06-11T18:38:54.222+08:00: Soft rlimits too low
        2021-06-11T18:38:54.222+08:00:         currentValue: 25000
        2021-06-11T18:38:54.222+08:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).
        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.
        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> show databases;  #查看所有数据库,但是只有三个数据库
admin   0.000GB
config  0.000GB
local   0.000GB
> show dbs         #查看所有数据库
admin   0.000GB
config  0.000GB
local   0.000GB
> db.getName()     #查看当前数据库,可以看到是test。test就是第四个库,也是mongodb默认登录的库
test

(3)MongoDB的操作


MongoDB中的命令是可以补齐的


-服务器相关操作

[root@mongodb ~]# mongo 192.168.100.202:27017  #先登录mongodb数据库
> db.help    #查看帮助信息
> help   #查看帮助信息
> db.version()  #查看版本
4.4.5

-数据库相关操作

> show databases  #查看所有数据库
admin   0.000GB
config  0.000GB
local   0.000GB
> show dbs   #查看所有数据库
admin   0.000GB
config  0.000GB
local   0.000GB
> use local  #进入local库
switched to db local
> db.getName() #查看当前在那个库中
local
> use aaa  #mongodb是不用创建库的,只需要进入之后创建集合,库就会自动生成
switched to db aaa
> db.getName()
aaa
> db.dropDatabase()  #删除当前库
{ "dropped" : "hehe", "ok" : 1 }
> show tables   #只要删除库,其库下的所有集合都会被删除
> show dbs  #查看所有库发现删除成功
admin   0.000GB
config  0.000GB
local   0.000GB


-集合相关操作

> use hehe       #进入hehe库
switched to db hehe
> db.getName()  
hehe
> db.aaa.insert({"id":1,"name":"zhangsan"})         #在当前库下创建集合aaa
WriteResult({ "nInserted" : 1 })       #这个1就表示创建成功
> show dbs      #创建完成后,发现多了一个库
admin   0.000GB
config  0.000GB
hehe    0.000GB
local   0.000GB
> show tables  #查看当前库中所有的表
aaa
> db.aaa.find()      #查看aaa集合中的所有表格
{ "_id" : ObjectId("60c370730e8947c79273ddfc"), "id" : 1, "name" : "zhangsan" }      #_id相当于主键,不指定的话,_id值是随机生成的
> db.aaa.insert({"id":2,"name":"lisi","favorite":["apple","banana","game"]}) #再次插入数据,值可以是列表
WriteResult({ "nInserted" : 1 })
> db.aaa.find()         #查看aaa集合中的所有表格
{ "_id" : ObjectId("60c370730e8947c79273ddfc"), "id" : 1, "name" : "zhangsan" }
{ "_id" : ObjectId("60c370ff0e8947c79273ddfd"), "id" : 2, "name" : "lisi", "favorite" : [ "apple", "banana", "game" ] }
> db.aaa.find({"id":2})       #筛选aaa集合中id键等于2的表格
{ "_id" : ObjectId("60c370ff0e8947c79273ddfd"), "id" : 2, "name" : "lisi", "favorite" : [ "apple", "banana", "game" ] }
> db.aaa.findOne({"id":1})  #使用findOne查看,输出信息更为简洁一点
{
  "_id" : ObjectId("60c370730e8947c79273ddfc"),
  "id" : 1,
  "name" : "zhangsan"
}
> db.aaa.findOne({"id":2})
{
  "_id" : ObjectId("60c370ff0e8947c79273ddfd"),
  "id" : 2,
  "name" : "lisi",
  "favorite" : [
    "apple",
    "banana",
    "game"
  ]
}
> a = db.aaa.findOne({"id":2})      #MongoDB中可以赋予变量名和变量值
{
  "_id" : ObjectId("60c370ff0e8947c79273ddfd"),
  "id" : 2,
  "name" : "lisi",
  "favorite" : [
    "apple",
    "banana",
    "game"
  ]
}
> a.id  #读取a中id键的值
2
> a.name  #读取a中name键的值
lisi
> db.aaa.findOne({"id":2}).id  #这两个和上面相同
2
> db.aaa.findOne({"id":2}).name
lisi
> db.aaa.insert({"id":3,"id":4,"name":"heheh","name":"bbbb"})   #插入多个相同键的值,查看效果
WriteResult({ "nInserted" : 1 })
> db.aaa.find()
{ "_id" : ObjectId("60c370730e8947c79273ddfc"), "id" : 1, "name" : "zhangsan" }
{ "_id" : ObjectId("60c370ff0e8947c79273ddfd"), "id" : 2, "name" : "lisi", "favorite" : [ "apple", "banana", "game" ] }
{ "_id" : ObjectId("60c372e30e8947c79273ddfe"), "id" : 4, "name" : "bbbb" }   #发现最后一个配置的键值会生效
> db.aaa.insert({"":22})    #键名可以为空,但是一般不会用
WriteResult({ "nInserted" : 1 })
> db.aaa.find()
{ "_id" : ObjectId("60c370730e8947c79273ddfc"), "id" : 1, "name" : "zhangsan" }
{ "_id" : ObjectId("60c370ff0e8947c79273ddfd"), "id" : 2, "name" : "lisi", "favorite" : [ "apple", "banana", "game" ] }
{ "_id" : ObjectId("60c372e30e8947c79273ddfe"), "id" : 4, "name" : "bbbb" }
{ "_id" : ObjectId("60c3733b0e8947c79273ddff"), "" : 22 }
> db.aaa.insert({"$id":4})  #键名不能以$开头
WriteResult({
  "nInserted" : 0,
  "writeError" : {
    "code" : 2,
    "errmsg" : "Document can't have $ prefixed field names: $id"
  }
})
> db.aaa.insert({"aaa$id":4})   #不能以$开头,但是可以包含$这种特殊字符
WriteResult({ "nInserted" : 1 })
> db.aaa.find()
{ "_id" : ObjectId("60c370730e8947c79273ddfc"), "id" : 1, "name" : "zhangsan" }
{ "_id" : ObjectId("60c370ff0e8947c79273ddfd"), "id" : 2, "name" : "lisi", "favorite" : [ "apple", "banana", "game" ] }
{ "_id" : ObjectId("60c372e30e8947c79273ddfe"), "id" : 4, "name" : "bbbb" }
{ "_id" : ObjectId("60c3733b0e8947c79273ddff"), "" : 22 }
{ "_id" : ObjectId("60c373970e8947c79273de01"), "aaa$id" : 4 }
> db.aaa.update({"id":1},{$set:{"name":"abc"}})  #修改aaa集合中,id键的值等于1的表格的name键改为abc
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.aaa.find()
{ "_id" : ObjectId("60c370730e8947c79273ddfc"), "id" : 1, "name" : "abc" }   #成功修改
{ "_id" : ObjectId("60c370ff0e8947c79273ddfd"), "id" : 2, "name" : "lisi", "favorite" : [ "apple", "banana", "game" ] }
{ "_id" : ObjectId("60c372e30e8947c79273ddfe"), "id" : 4, "name" : "bbbb" }
{ "_id" : ObjectId("60c3733b0e8947c79273ddff"), "" : 22 }
{ "_id" : ObjectId("60c373970e8947c79273de01"), "aaa$id" : 4 }
> for(i=1;i<=1000;i++){db.abc.insert({"id":i,"name":"hehe"})}  #mongodb的数据库可以使用循环语句,利用for循环创建集合
WriteResult({ "nInserted" : 1 })
> show tables  #查看当前库中所有的表
aaa
abc
> db.abc.find()   #查看发现一页只能显示20行,出入it可以翻页
{ "_id" : ObjectId("60c374b20e8947c79273de02"), "id" : 1, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de03"), "id" : 2, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de04"), "id" : 3, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de05"), "id" : 4, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de06"), "id" : 5, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de07"), "id" : 6, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de08"), "id" : 7, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de09"), "id" : 8, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0a"), "id" : 9, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0b"), "id" : 10, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0c"), "id" : 11, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0d"), "id" : 12, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0e"), "id" : 13, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0f"), "id" : 14, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de10"), "id" : 15, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de11"), "id" : 16, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de12"), "id" : 17, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de13"), "id" : 18, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de14"), "id" : 19, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de15"), "id" : 20, "name" : "hehe" }
Type "it" for more
> it    #输入it翻页
{ "_id" : ObjectId("60c374b20e8947c79273de16"), "id" : 21, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de17"), "id" : 22, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de18"), "id" : 23, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de19"), "id" : 24, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de1a"), "id" : 25, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de1b"), "id" : 26, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de1c"), "id" : 27, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de1d"), "id" : 28, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de1e"), "id" : 29, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de1f"), "id" : 30, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de20"), "id" : 31, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de21"), "id" : 32, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de22"), "id" : 33, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de23"), "id" : 34, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de24"), "id" : 35, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de25"), "id" : 36, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de26"), "id" : 37, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de27"), "id" : 38, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de28"), "id" : 39, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de29"), "id" : 40, "name" : "hehe" }
Type "it" for more
> db.abc.remove({"id":1})  #删除集合中id键的值等于1的表格
WriteResult({ "nRemoved" : 1 })
> db.abc.find()
{ "_id" : ObjectId("60c374b20e8947c79273de03"), "id" : 2, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de04"), "id" : 3, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de05"), "id" : 4, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de06"), "id" : 5, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de07"), "id" : 6, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de08"), "id" : 7, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de09"), "id" : 8, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0a"), "id" : 9, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0b"), "id" : 10, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0c"), "id" : 11, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0d"), "id" : 12, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0e"), "id" : 13, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de0f"), "id" : 14, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de10"), "id" : 15, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de11"), "id" : 16, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de12"), "id" : 17, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de13"), "id" : 18, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de14"), "id" : 19, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de15"), "id" : 20, "name" : "hehe" }
{ "_id" : ObjectId("60c374b20e8947c79273de16"), "id" : 21, "name" : "hehe" }
Type "it" for more
> db.abc.drop()   #删除当前库下的abc集合
true      #true表示删除成功
> show tables  #查看所有集合发现删除成功
aaa


-MongoDB数据库的用户角色权限管理


角色类型 权限级别
普通用户角色 read.readWwrite 读和读写
数据库管理员角色 dbAdmin、dbOwner、userAdmin
集群管理员角色 clusterAdmin.clusterManager.clusterMonitor、hostManager
数据库备份与恢复角色 backup、restore
所有数据库角色 readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
超级用户角色 root
核心角色 __system



普通用户角色:


read: 提供了读取所有非系统集合的权限,以及系统集合中的system.indexes, system.js, system.namespaces


readWrite: 包含了所有read权限,以及修改所有非系统集合的和系统集合中的system.js的权限


数据库管理员角色:


dbOwner:该数据库的所有者,具有该数据库的全部权限


dbAdmin:一些数据库对象的管理操作,但是没有数据库的读写权限。


userAdmin:为当前用户创建、修改用户和角色。拥有userAdmin权限的用户可以将该数据库的任意权限赋予任意的用户。


集群管理员角色:


clusterAdmin:提供了最大的集群管理功能。相当于clusterManager, clusterMonitor, and hostManager和dropDatabase的权限组合。


clusterManager:提供了集群和复制集管理和监控操作。拥有该权限的用户可以操作config和local数据库(即分片和复制功能)


clusterMonitor:仅仅监控集群和复制集。


hostManager:提供了监控和管理服务器的权限,包括shutdown节点,logrotate, repairDatabase等。


数据库备份与恢复角色:


admin数据库中包含了备份恢复数据的角色。包括backup、restore等等


所有数据库角色:


admin数据库提供了一个mongod实例中所有数据库的权限角色


readAnyDatabase: 具有read每一个数据库权限。但是不包括应用到集群中的数据库。和read相似,但它是全局。的。


readWriteAnyDatabase: 具有readWrite每一个数据库权限。但是不包括应用到集群中的数据库。


userAdminAnyDatabase: 具有userAdmin每一个数据库权限,但是不包括应用到集群中的数据库。


dbAdminAnyDatabase: 提供了dbAdmin每一个数据库权限,但是不包括应用到集群中的数据库。


超级管理员权限:


**root: ** dbadmin到admin数据库、useradmin到admin数据库以及UserAdminAnyDatabase。但它不具有备份恢复、直接操作system.*集合的权限,但是拥有root权限的超级用户可以自己给自己赋予这些权限。


注意:!!!!!!!!!!!!!!


创建用户时,需要在默认test数据库中,不use到任何数据库


查看扫描用户时,需要在admin数据库中,执行use admin切换进去


撤销修改时,需要在用户所属的db数据库中进行

[root@mongodb ~]# mongo 192.168.100.202:27017
> db.getName()  #确认当前数据库是test
test 
> db.getUsers() #查看所有用户,默认是没有的
[ ] 
> db.createUser({user:"Boss",pwd:"123123",roles:[{role:"root",db:"admin"}]})  #创建用户,用户名Boss,密码123123,权限为root,管理的库为当前库和admin库
Successfully added user: {
  "user" : "Boss",
  "roles" : [
    {
      "role" : "root",
      "db" : "admin"
    }
  ]
}
> db.getUsers()
[
  {
    "_id" : "test.Boss",
    "userId" : UUID("52252c8b-d569-40c9-9d0d-ec3906bff198"),
    "user" : "Boss",
    "db" : "test",
    "roles" : [
      {
        "role" : "root",
        "db" : "admin"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  }
]
> exit
bye
[root@mongodb ~]# mongod -f /usr/local/mongodb/conf/mongodb.conf --shutdown  #先关闭mongodb
killing process with pid: 1030
[root@mongodb ~]# mongod -f /usr/local/mongodb/conf/mongodb.conf --auth  #临时开启用户认证,永久开启需要在主配置文件中加auth=yes即可
about to fork child process, waiting until server is ready for connections.
forked process: 15837
child process started successfully, parent exiting
[root@mongodb ~]# mongod -f /usr/local/mongodb/conf/mongodb.conf --shutdown
killing process with pid: 15837
[root@mongodb ~]# echo "auth=yes" >> /usr/local/mongodb/conf/mongodb.conf   #写入配置文件
[root@mongodb ~]# mongod -f /usr/local/mongodb/conf/mongodb.conf 
about to fork child process, waiting until server is ready for connections.
forked process: 15878
child process started successfully, parent exiting
[root@mongodb ~]# netstat -anpt | grep mongo
tcp        0      0 192.168.100.202:27017   0.0.0.0:*               LISTEN      15878/mongod   
[root@mongodb ~]# mongo 192.168.100.202:27017  #这个时候直接登录数据库查看效果
MongoDB shell version v4.4.5
connecting to: mongodb://192.168.100.202:27017/test?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("57cd0af4-17c9-44ab-9523-5e58130709d0") }
MongoDB server version: 4.4.5
> show dbs  #发现查看不了任何东西
> show databases
> use aaa
switched to db aaa
> show tables
Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus
> exit
bye
> db.auth("Boss","123123")   #登录刚才授权的用户
1   #1为登录成功
> show dbs  #现在就可以查看了
admin   0.000GB
cat     0.000GB
config  0.000GB
local   0.000GB
> use aaa
switched to db aaa
> db.hehe.insert({"id":1,"name":"chengzhuang"})  #并且可以创建集合和库
WriteResult({ "nInserted" : 1 })
> db.hehe.find()
{ "_id" : ObjectId("60c38ee966fde8910d41f09f"), "id" : 1, "name" : "chengzhuang" }
> db.createUser({user:"hehe",pwd:"123123",roles:[{role:"read",db:"aaa"},{role:"readWrite",db:"cat"}]})  #创建用户hehe密码123123,对aaa库有读的权限,对cat有读写的权限
Successfully added user: {
  "user" : "hehe",
  "roles" : [
    {
      "role" : "read",
      "db" : "aaa"
    },
    {
      "role" : "readWrite",
      "db" : "cat"
    }
  ]
}
> db.getUsers() #查看所有用户
[
  {
    "_id" : "test.Boss",
    "userId" : UUID("52252c8b-d569-40c9-9d0d-ec3906bff198"),
    "user" : "Boss",
    "db" : "test",
    "roles" : [
      {
        "role" : "root",
        "db" : "admin"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  },
  {
    "_id" : "test.hehe",
    "userId" : UUID("59cd2d85-47b2-48cf-9c48-067ddba41470"),
    "user" : "hehe",
    "db" : "test",
    "roles" : [
      {
        "role" : "read",
        "db" : "aaa"
      },
      {
        "role" : "readWrite",
        "db" : "cat"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  }
]
> db.auth("hehe","123123")  #登录hehe用户
1
> use aaa
switched to db aaa
> show tables  #进入aaa库查看集合
hehe
> db.hehe.find()  #查看hehe集合的数据
{ "_id" : ObjectId("60c38ee966fde8910d41f09f"), "id" : 1, "name" : "chengzhuang" }
> db.hehe.insert({"id":2,"name":aaaa})  #发现无法写入集合,因为hehe用户对aaa库只有读的权限
uncaught exception: ReferenceError: aaaa is not defined :
@(shell):1:24
> use cat
switched to db cat
> show tables
> db.haha.insert({"id":1,"name":"sssss"})  #创建haha集合并写入数据
WriteResult({ "nInserted" : 1 })
> show tables
haha
> db.haha.find()   #对cat库有读写的权限
{ "_id" : ObjectId("60c392aab8318bbee3646402"), "id" : 1, "name" : "sssss" }
> exit
bye
[root@mongodb ~]# mongo 192.168.100.202:27017  #重新进r数据库
MongoDB shell version v4.4.5
connecting to: mongodb://192.168.100.202:27017/test?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("205c9a68-65f1-4049-ba72-51c5eca16fd6") }
MongoDB server version: 4.4.5
> db.auth("Boss","123123")  #登录boss用户
1
> db.grantRolesToUser("hehe",[{role:"readWrite",db:"aaa"}])  #为hehe用户添加aaa库的读写权限
> db.getUsers()   #查看权限
[
  {
    "_id" : "test.Boss",
    "userId" : UUID("52252c8b-d569-40c9-9d0d-ec3906bff198"),
    "user" : "Boss",
    "db" : "test",
    "roles" : [
      {
        "role" : "root",
        "db" : "admin"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  },
  {
    "_id" : "test.hehe",
    "userId" : UUID("59cd2d85-47b2-48cf-9c48-067ddba41470"),
    "user" : "hehe",
    "db" : "test",
    "roles" : [
      {
        "role" : "readWrite",  
        "db" : "cat"
      },
      {
        "role" : "readWrite",  #发现多了一个对aaa库的读写权限
        "db" : "aaa"
      },
      {
        "role" : "read",
        "db" : "aaa"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  }
]
> db.system.users.find()    #扫描所有用户以及权限
> db.revokeRolesFromUser("hehe",[{role:"readWrite",db:"aaa"}])   #移除用户hehe对aaa库的读写权限
> db.getUsers()  #查看所有用户的权限
[
  {
    "_id" : "test.Boss",
    "userId" : UUID("52252c8b-d569-40c9-9d0d-ec3906bff198"),
    "user" : "Boss",
    "db" : "test",
    "roles" : [
      {
        "role" : "root",
        "db" : "admin"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  },
  {
    "_id" : "test.hehe",
    "userId" : UUID("59cd2d85-47b2-48cf-9c48-067ddba41470"),
    "user" : "hehe",
    "db" : "test",
    "roles" : [
      {
        "role" : "read",   #发现少了对aaa库的读写权限
        "db" : "aaa"
      },
      {
        "role" : "readWrite",
        "db" : "cat"
      }
    ],
    "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  }
]
> db.system.users.remove({user:"hehe"})   #删除用户hehe
WriteResult({ "nRemoved" : 1 })    #删除成功
> exit
bye
[root@mongodb ~]# mongo --host 192.168.100.202 --port 27017 -u Boss -p 123123 --authenticationDatabase test
#-u指定用户名,-p指定用户的密码,--authenticationDatabase创建用户时所在库
> db.getName()
test
[root@mongodb ~]# mongo 192.168.100.202:27017/test -u Boss -p 123123  #两种登录方式
> 

-复制数据库


语法: db.copyDatabase(fromdb, todb, fromhost, username, password)


fromdb: 字符串类型,输入用户源数据库的名称,前提是用户必须能对指定数据库进行鉴权


todb: 字符串类型,复制到的目的数据库的名称,名称可以和之前的不一样


fromhost: 字符串类型,可选项,输入目标ip加端口号,如果是本机则可以忽略


username: 字符串类型,可选项,源主机用户名


password: 字符串类型,可选项,源主机用户的密码


复制数据库: db.copyDatabase(“source_db”,“des_db”,“192.168.100.102”)


克隆集合: db.runCommand({cloneCollection:“accp.t1”,from:“192.168.100.102:27017”})


三版本的可以这样复制,四版本的这样复制不了


(4)MongoDB的备份、恢复


MongoDB数据库可以将mysql数据库的数据导入到自己的库中


Mongoimport 能够还原json文件的数据

[root@mongodb ~]# yum -y install mysql mariadb-server
。。。。。。
完毕!
[root@mongodb ~]# systemctl start mariadb
[root@mongodb ~]# mysql 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.56-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> create database  aaa;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> use aaa
Database changed
MariaDB [aaa]> create table aaa(id int,name char(12));
Query OK, 0 rows affected (0.39 sec)
MariaDB [aaa]> insert into aaa values(1,"zhangsan");
Query OK, 1 row affected (0.00 sec)
MariaDB [aaa]> insert into aaa values(2,"lisi");
Query OK, 1 row affected (0.00 sec)
MariaDB [aaa]> select * from aaa;
+------+----------+
| id   | name     |
+------+----------+
|    1 | zhangsan |
|    2 | lisi     |
+------+----------+
2 rows in set (0.00 sec)
MariaDB [aaa]> select * from  aaa.aaa into outfile '/tmp/aaa-aaa_mysql.csv' fields terminated by ",";  
#查看aaa库下的aaa表中的所有数据并且保存到/tmp/aaa-aaa_mysql.csv路径下,并且以“,”分割开来
Query OK, 2 rows affected (0.00 sec)
MariaDB [aaa]> exit
Bye
[root@mongodb tmp]# cd systemd-private-8911216114974ba6910ebdb73bb6fc02-mariadb.service-31jtXY/ #mariadb是保存在这个路径下的
[root@mongodb systemd-private-8911216114974ba6910ebdb73bb6fc02-mariadb.service-31jtXY]# ll
总用量 0
drwxrwxrwt 2 root root 31 6月  11 22:50 tmp
[root@mongodb systemd-private-8911216114974ba6910ebdb73bb6fc02-mariadb.service-31jtXY]# cd tmp/
[root@mongodb tmp]# ll   #发现有刚才保存的文件
总用量 4
-rw-rw-rw- 1 mysql mysql 18 6月  11 22:50 aaa-aaa_mysql.csv  
[root@mongodb tmp]# cat aaa-aaa_mysql.csv   #查看此文件
1,zhangsan
2,lisi
[root@mongodb tmp]# cd
[root@mongodb ~]# mongoimport --port 27017 --host 192.168.100.202 -d cat  -c dog -f id,name --file /tmp/systemd-private-8911216114974ba6910ebdb73bb6fc02-mariadb.service-31jtXY/tmp/aaa-aaa_mysql.csv --type csv  #mongoimport是mongodb的导入命令-d指定导入的数据库,-c指定导入的集合,-f指定导入文档的键,--file指定文件路径--type指定导入文件类型
2021-06-11T22:58:00.628+0800  connected to: mongodb://192.168.100.202:27017/
2021-06-11T22:58:00.633+0800  2 document(s) imported successfully. 0 document(s) failed to import.
[root@mongodb ~]# mongo 192.168.100.202:27017 #进入数据库
。。。。。。
> show dbs  #查看所有库,发现多了cat库
admin   0.000GB
cat     0.000GB
config  0.000GB
local   0.000GB
> use cat
switched to db cat
> show tables  #进入cat库查看当下库的所有集合,发现有一个dog集合
dog
> db.dog.find()  #查看dog集合,发现数据成功导入
{ "_id" : ObjectId("60c379f80647130a766fc833"), "id" : 1, "name" : "zhangsan" }
{ "_id" : ObjectId("60c379f80647130a766fc834"), "id" : 2, "name" : "lisi" }
> for(var i=1;i<=10000;i++)db.dog.insert({"id":i,"name":"name"+i})  #使用for循环写集合
WriteResult({ "nInserted" : 1 })
> db.dog.find({"id":{"$gt":5000}}).limit(3)  #查看id大于5000的,并且只显示三行
{ "_id" : ObjectId("60c37b7dd9f823fa7cd0b5bf"), "id" : 5001, "name" : "name5001" }
{ "_id" : ObjectId("60c37b7dd9f823fa7cd0b5c0"), "id" : 5002, "name" : "name5002" }
{ "_id" : ObjectId("60c37b7dd9f823fa7cd0b5c1"), "id" : 5003, "name" : "name5003" }
> db.dog.find({"id":{"$gt":5000}}).count() #查看id大于5000的并统计
5000
> db.dog.insert({"id":111111,"name":"name"}) #再插入一行文档
WriteResult({ "nInserted" : 1 })
> db.dog.find({"id":{"$gt":5000}}).count()  #统计
5001
> exit
[root@mongodb ~]# mongoexport --host 192.168.100.202 --port 27017 -d cat -c dog -q '{"id":{"$lt":5000}}' -o /root/cat.json   #mongoexport是mongodb用于导出数据的命令,-q可以指定条件否则会把所有的都导出来,-o指定路径
2021-06-11T23:09:54.234+0800  connected to: mongodb://192.168.100.202:27017/
2021-06-11T23:09:54.422+0800  exported 5001 records
[root@mongodb ~]# head -3 cat.json 
{"_id":{"$oid":"60c379f80647130a766fc833"},"id":1,"name":"zhangsan"}
{"_id":{"$oid":"60c379f80647130a766fc834"},"id":2,"name":"lisi"}
{"_id":{"$oid":"60c37b7cd9f823fa7cd0a237"},"id":1.0,"name":"name1"}
[root@mongodb ~]# cat cat.json | wc -l
5001
[root@mongodb ~]# mongo 192.168.100.202:27017
> use cat
switched to db cat
> show tables
dog
> db.dog.drop()
true
> show tables
> exit
bye
[root@mongodb ~]# mongoimport --port 27017 --host 192.168.100.202  -d cat -c dog --file /root/cat.json #再次导入,json类型的文件是不需要指定类型的 
2021-06-11T23:14:02.428+0800  connected to: mongodb://192.168.100.202:27017/
2021-06-11T23:14:02.490+0800  5001 document(s) imported successfully. 0 document(s) failed to import.
[root@mongodb ~]# mongo 192.168.100.202:27017
> use cat 
switched to db cat
> show tables
dog
> db.dog.find().count() #进行统计,发现恢复成功
5001

Mongorestore 能够还原bson文件的数据

[root@mongodb ~]# mkdir backup
[root@mongodb ~]# mongodump --host 192.168.100.202 --port 27017 -d cat -o backup/
2021-06-11T23:17:59.645+0800  writing cat.dog to backup/cat/dog.bson
2021-06-11T23:17:59.649+0800  done dumping cat.dog (5001 documents)
[root@mongodb ~]# ll backup/
总用量 0
drwxr-xr-x 2 root root 47 6月  11 23:17 cat
[root@mongodb ~]# ll backup/cat/
总用量 264
-rw-r--r-- 1 root root 263934 6月  11 23:17 dog.bson
-rw-r--r-- 1 root root    150 6月  11 23:17 dog.metadata.json
[root@mongodb ~]# mongo 192.168.100.202:27017/cat  #在后面可以指定进入的数据库,不知道默认进入test库
> db.getName()
cat
> show tables
dog
> db.dog.drop()
true
> show tables
> exit
bye
[root@mongodb ~]# mongorestore --host 192.168.100.202 --port 27017 -d cat --dir=backup/cat/   #--dir指定路径
2021-06-11T23:22:42.748+0800  The --db and --collection flags are deprecated for this use-case; please use --nsInclude instead, i.e. with --nsInclude=${DATABASE}.${COLLECTION}
2021-06-11T23:22:42.749+0800  building a list of collections to restore from backup/cat dir
2021-06-11T23:22:42.749+0800  reading metadata for cat.dog from backup/cat/dog.metadata.json
2021-06-11T23:22:42.755+0800  restoring cat.dog from backup/cat/dog.bson
2021-06-11T23:22:42.858+0800  no indexes to restore
2021-06-11T23:22:42.858+0800  finished restoring cat.dog (5001 documents, 0 failures)
2021-06-11T23:22:42.858+0800  5001 document(s) restored successfully. 0 document(s) failed to restore.
[root@mongodb ~]# mongo 192.168.100.202:27017/cat
> show tables  #发现成功
dog


相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
1月前
|
NoSQL 容灾 MongoDB
MongoDB主备副本集方案:两台服务器使用非对称部署的方式实现高可用与容灾备份
在资源受限的情况下,为了实现MongoDB的高可用性,本文探讨了两种在两台服务器上部署MongoDB的方案。方案一是通过主备身份轮换,即一台服务器作为主节点,另一台同时部署备节点和仲裁节点;方案二是利用`priority`设置实现自动主备切换。两者相比,方案二自动化程度更高,适合追求快速故障恢复的场景,而方案一则提供了更多的手动控制选项。文章最后对比了这两种方案与标准三节点副本集的优缺点,指出三节点方案在高可用性和数据一致性方面表现更佳。
|
1月前
|
存储 NoSQL MongoDB
【赵渝强老师】部署MongoDB复制集
本文介绍了如何在单个节点上搭建MongoDB复制集环境,通过监听不同端口实现多节点配置。详细步骤包括创建数据目录、编辑配置文件、启动节点、初始化复制集、查看状态以及测试主从库的读写操作。文中还提供了视频讲解和代码示例,帮助读者更好地理解和操作。
|
3月前
|
存储 NoSQL MongoDB
01 MongoDB的概述、应用场景、下载方式、连接方式和发展历史等
文章详细介绍了MongoDB的概览、应用场景、下载与连接方式,并涵盖了MongoDB的主要特性及其在数据存储方面的优势。
39 0
|
4月前
|
存储 NoSQL MongoDB
今日分享MongoDB一键部署脚本
今日分享MongoDB一键部署脚本
39 0
|
4月前
|
存储 NoSQL MongoDB
八:《智慧的网络爬虫》— MongoDB概述
【8月更文挑战第14天】本篇文章简单介绍了MongoDB的下载和安装以;其基本的操作语法,并附上每个语法的代码示例,为后续的爬虫学习打下基础
52 0
八:《智慧的网络爬虫》— MongoDB概述
|
5月前
|
JSON NoSQL 关系型数据库
MongoDB常用命令大全,概述、备份恢复
MongoDB常用命令大全:服务启动停止、查看状态、备份;数据库相关,集合操作,文档操作,其他常用命令;数据备份恢复/导入导出——mongodump、mongorestore;MongoDB与SQL比较
|
7月前
|
NoSQL Unix MongoDB
【docker 】docker-compose 部署mongoDB
【docker 】docker-compose 部署mongoDB
223 1
|
7月前
|
NoSQL MongoDB 数据库
docker部署mongoDB
docker部署mongoDB
230 0
|
7月前
|
存储 NoSQL 物联网
【MongoDB】MongoDB 数据库概述
【4月更文挑战第1天】【MongoDB】MongoDB 数据库概述
【MongoDB】MongoDB 数据库概述
|
7月前
|
NoSQL JavaScript Linux
【MongoDB系列相关笔记】单机部署
本文主要介绍了Windows和Linux系统中安装和启动MongoDB的步骤。
177 0
下一篇
DataWorks