登录认证:db.auth( <username>, <password> )
查看账号:db.system.users.find();
修改密码:db.changeUserPassword("reporting", "123456")
1:添加一个products的readWrite和dbAdmin账号
use products db.createUser( { user: "accountUser", pwd: "password", roles: [ "readWrite", "dbAdmin" ] } )
登录:db.auth('accountUser','password')
2:添加一个maxiangqian的只读账号
db.createUser( { user: "maxiangqian", pwd: "maxiangqian", roles: [ { role: "Read", db: "maxiangqian" } ] } )
登录:db.auth('maxiangqian','maxiangqian')
3:添加一个空用户
use admin db.createUser( { user: "reportsUser", pwd: "password", roles: [ ] } )
4:添加一个超级管理员账号
use admin db.createUser( { user: "maxiangqian", pwd: "maxiangqian", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) db.auth('maxiangqianadmin','maxiangqianadmin')
5:admin数据库添加读写权限和群集管理员权限
use admin db.createUser( { user: "appAdmin", pwd: "password", roles: [ { role: "readWrite", db: "config" }, "clusterAdmin" ] } ) db.updateUser()
语法格式如下:
db.updateUser( "<username>", { customData : { <any information> }, roles : [ { role: "<role>", db: "<database>" } | "<role>", ... ], pwd: "<cleartext password>" }, writeConcern: { <write concern> } )
修改密码:db.changeUserPassword()
db.changeUserPassword("accountUser", "SOh3TbYhx8ypJPxmt1oOfL")
删除用户:db.removeUser(username)
db.dropAllUsers( {w: "majority", wtimeout: 5000} )
删除某个用户:
use products db.dropUser("reportUser1", {w: "majority", wtimeout: 5000})
授予账号权限:
db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )
例子
use products db.grantRolesToUser( "accountUser01", [ "readWrite" , { role: "read", db: "stock" } ], { w: "majority" , wtimeout: 4000 } )
收回权限:
db.revokeRolesFromUser( "<username>", [ <roles> ], { <writeConcern> } )
例子:(The following db.revokeRolesFromUser() method removes the two of the user’s roles: the read role on the stock database and the readWrite role on the products database)
use products db.revokeRolesFromUser( "accountUser01", [ { role: "read", db: "stock" }, "readWrite" ], { w: "majority" } )
获取当前用户权限:
use accounts db.getUser("appClient")
账号角色以及权限:
1,内建的角色
2,数据库用户角色:read、readWrite;
3,数据库管理角色:dbAdmin、dbOwner、userAdmin;
4,集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
5,备份恢复角色:backup、restore;
6,所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
7,超级用户角色:root // 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)
8,内部角色:__system
角色说明:
Read:允许用户读取指定数据库
readWrite:允许用户读写指定数据库
dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
root:只在admin数据库中可用。超级账号,超级权限