MongoDB的用户,角色操作

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_23035335/article/details/99545757

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"})

猜你喜欢

转载自blog.csdn.net/qq_23035335/article/details/99545757