定义
grantRolesToUser授予用户其他角色。
提示
In
mongosh, this command can also be run through thedb.grantRolesToUser()helper method.Helper methods are convenient for
mongoshusers, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.
兼容性
此命令可用于以下环境中托管的部署:
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
重要
This command is not supported in MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
语法
The grantRolesToUser command uses the following syntax:
db.runCommand( { grantRolesToUser: "<user>", roles: [ <roles> ], writeConcern: { <write concern> }, comment: <any> } )
命令字段
该命令接受以下字段:
字段 | 类型 | 说明 |
|---|---|---|
| 字符串 | 用于赋予其他角色的用户名称。 |
| 阵列 | 授予用户的附加角色的数组。 |
| 文档 | |
| any | 可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:
注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。 |
To specify a role that exists in the same database where grantRolesToUser runs, you can either specify the role with the name of the role:
"readWrite"
或者,可以使用文档指定角色,如下所示:
{ role: "<role>", db: "<database>" }
要指定存在于其他数据库中的角色,请使用文档指定该角色。
必需的访问权限
例子
假设 products 数据库中有一个具有以下角色的用户 accountUser01:
"roles" : [ { "role" : "assetsReader", "db" : "assets" } ]
The following grantRolesToUser operation gives accountUser01 the read role on the stock database and the readWrite role on the products database.
use products db.runCommand( { grantRolesToUser: "accountUser01", roles: [ { role: "read", db: "stock"}, "readWrite" ], writeConcern: { w: "majority" , wtimeout: 2000 } } )
products 数据库中的用户 accountUser01 现在具有以下角色:
"roles" : [ { "role" : "assetsReader", "db" : "assets" }, { "role" : "read", "db" : "stock" }, { "role" : "readWrite", "db" : "products" } ]