定义
db.grantRolesToUser(username, roles, writeConcern)授予用户其他角色。
重要
mongosh 方法
本页介绍了
mongosh方法。这不是数据库命令或特定语言驱动程序(例如 Node.js)的文档。有关数据库命令,请参阅
grantRolesToUser命令。如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
db.grantRolesToUser()方法使用以下语法:db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } ) db.grantRolesToUser()方法接受以下参数:要指定运行
db.grantRolesToUser()的同一数据库中存在的角色,可以使用角色名称指定角色:"readWrite" 或者,可以使用文档指定角色,如下所示:
{ role: "<role>", db: "<database>" } 要指定存在于其他数据库中的角色,请使用文档指定该角色。
兼容性
此方法可用于以下环境中托管的部署:
重要
MongoDB Atlas 集群不支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
副本集
如果在副本集上运行,则默认使用 写关注(write concern)执行db.grantRolesToUser() "majority"。
必需的访问权限
例子
假设 products 数据库中有一个具有以下角色的用户 accountUser01:
"roles" : [ { "role" : "assetsReader", "db" : "assets" } ]
以下db.grantRolesToUser() 操作为accountUser01 readWrite赋予了products 数据库上的 角色和read stock数据库上的 角色。
use products db.grantRolesToUser( "accountUser01", [ "readWrite" , { role: "read", db: "stock" } ], { w: "majority" , wtimeout: 4000 } )
products 数据库中的用户 accountUser01 现在具有以下角色:
"roles" : [ { "role" : "assetsReader", "db" : "assets" }, { "role" : "read", "db" : "stock" }, { "role" : "readWrite", "db" : "products" } ]