定义
grantPrivilegesToRole为运行命令的数据库上定义的 用户定义 角色分配其他 权限 。
提示
In
mongosh, this command can also be run through thedb.grantPrivilegesToRole()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.The
grantPrivilegesToRolecommand uses the following syntax:
db.runCommand( { grantPrivilegesToRole: "<role>", privileges: [ { resource: { <resource> }, actions: [ "<action>", ... ] }, ... ], writeConcern: { <write concern> }, comment: <any> } )
兼容性
此命令可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
重要
This command is not supported in M0 and Flex clusters. For more information, see Unsupported Commands.
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
命令字段
该命令具有以下字段:
字段 | 类型 | 说明 |
|---|---|---|
| 字符串 | 要授予权限的用户定义角色的名称。 |
| 阵列 | 要添加到角色的权限。有关权限的格式,请参阅 |
| 文档 | |
| any | 可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:
注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。 |
行为
角色的权限适用于创建该角色的数据库。在admin数据库上创建的角色可以包含适用于所有数据库或集群的权限。
必需的访问权限
您必须对权限的目标数据库执行 grantRole 操作才能授予该权限。要授予对多个数据库或 cluster 资源的权限,必须对 admin 数据库执行 grantRole 操作。
例子
The following grantPrivilegesToRole command grants two additional privileges to the service role that exists in the products database:
use products db.runCommand( { grantPrivilegesToRole: "service", privileges: [ { resource: { db: "products", collection: "" }, actions: [ "find" ] }, { resource: { db: "products", collection: "system.js" }, actions: [ "find" ] } ], writeConcern: { w: "majority" , wtimeout: 5000 } } )
privileges大量中的第一个权限允许用户搜索products数据库中的所有非系统集合。 该权限不允许对系统集合进行查询,例如system.js集合。 要授予访问权限这些系统集合的访问权限,请在privileges大量中显式预配访问权限。 请参阅有关自管理部署的资源文档。