MongoDB的用户,角色操作

1.基本知识介绍

MongoDB基本的角色

1.数据库用户角色:read、readWrite;
2.数据库管理角色:dbAdmin、dbOwner、userAdmin;
3.集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4.备份恢复角色:backup、restore;
5.所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6.超级用户角色:root  
//这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)

其中MongoDB默认是没有开启用户认证的,也就是说游客也拥有超级管理员的权限。生产环境会开启用户验证。userAdminAnyDatabase:有分配角色和用户的权限,但没有查写的权限。

如果一个用户是userAdminAnyDatabase的角色,是可以分配角色和用户的,但是不能查写其他数据库里的数据,会报如下错误:要查写其它数据库的数据可以设置为root角色。

Can't read collections
  Command failed with error 13 (Unauthorized): 'not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: "civilization" }' on server 47.107.255.249:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: \"civilization\" }", "code" : 13, "codeName" : "Unauthorized" }
  Command failed with error 13 (Unauthorized): 'not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: "civilization" }' on server 47.107.255.249:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: \"civilization\" }", "code" : 13, "codeName" : "Unauthorized" }


2、操作步骤

创建用户:在admin数据库里面创建用户(use database,如果这个database不存在就会自动创建,但是如果里面没数据的话是查不到这个数据库的,show dbs:列出所有数据库)

>use admin

>db.createUser({user:"root",pwd:"password",roles:["root"]})

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

修改MongoDB的配置文件后,得重启MongoDB数据库。

vi /etc/mongodb.conf

systemctl restart mongodb.service

创建新数据库新用户:MongoDB开启验证后,登录root用户,创建新的数据库和可以操作该数据库读写的用户

>use admin

>db.auth("root","password");

>use footdatabase

>db.createUser({
    user: "foot",
    pwd: "password",
    roles: [{role: "readWrite",db: "footdatabase"}]
})

修改密码角色:修改用户密码,角色,如果只修改密码就可以不写roles,就不会更改角色

> db.updateUser('root',{pwd:'654321',roles:[{role:'root',db:'admin'}]})

删除用户:如果忘记root密码,可以修改配置文件为不验证,重启MongoDB,连接进入后删除root用户,再重新创建root用户,除用户(需要root权限,会将所有数据库中的用户名为foot用户删除,如果remove不传参数,那就是删除所有用户

>use admin

>db.system.users.remove({user:"foot"});

关闭mongo,该命令要在root管理员权限下执行

>use admin

>db.shutdownServer()  

PS:为了使MongoDB的可视化工具能看到创建的数据库,可以随便往数据库里插入一条数据

>db.test_col.insert({test:"test"})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值