grantPrivilegesToRole
定义
grantPrivilegesToRole
Assigns additional privileges to a user-defined role defined on the database on which the command is run.
提示
在
mongosh
中,该命令也可通过db.grantPrivilegesToRole()
辅助方法运行。辅助方法对
mongosh
用户来说很方便,但它们返回的信息级别可能与数据库命令不同。如果不追求方便或需要额外的返回字段,请使用数据库命令。grantPrivilegesToRole
命令使用以下语法:
db.runCommand( { grantPrivilegesToRole: "<role>", privileges: [ { resource: { <resource> }, actions: [ "<action>", ... ] }, ... ], writeConcern: { <write concern> }, comment: <any> } )
兼容性
此命令可用于以下环境中托管的部署:
MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
重要
M 0 、M 2和 M 5集群不支持此命令。 有关更多信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
命令字段
该命令具有以下字段:
字段 | 类型 | 说明 |
---|---|---|
| 字符串 | The name of the user-defined role to grant privileges to. |
| 阵列 | 要添加到角色的权限。有关权限的格式,请参阅 |
| 文档 | |
| any | 可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:
注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。 |
行为
A role's privileges apply to the database where the role is created. A
role created on the admin
database can include privileges that apply
to all databases or to the 集群.
必需的访问权限
您必须对权限的目标数据库执行 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 } } )
The first privilege in the privileges
array allows the user to
search on all non-system collections in the products
database. The
privilege does not allow queries on system collections, such as the system.js
collection. To grant access to these
system collections, explicitly provision access in the privileges
array. See 有关自管理部署的资源文档.
The second privilege explicitly allows the find
action on
system.js
collections on all
databases.