Docs 主页 → 开发应用程序 → MongoDB Manual
grantPrivilegesToRole
定义
grantPrivilegesToRole
为运行命令的数据库上定义的 用户定义 角色分配其他 权限 。
提示
在
mongosh
中,该命令也可以通过db.grantPrivilegesToRole()
辅助方法运行。助手方法对于
mongosh
用户来说很方便,但它们返回的信息级别可能与数据库命令不同。如果不追求方便或需要额外的返回字段,请使用数据库命令。grantPrivilegesToRole
命令使用以下语法:{ grantPrivilegesToRole: "<role>", privileges: [ { resource: { <resource> }, actions: [ "<action>", ... ] }, ... ], writeConcern: { <write concern> }, comment: <any> } grantPrivilegesToRole
命令具有以下字段:字段类型说明grantPrivilegesToRole
字符串要授予权限的用户定义角色的名称。privileges
阵列要添加到角色的权限。有关权限的格式,请参阅privileges
。writeConcern
文档comment
注意到可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:
mongod 日志消息,位于
attr.command.cursor.comment
字段中。command.comment
字段中的数据库分析器输出。currentOp
输出,在command.comment
字段。
注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。
行为
角色的权限适用于创建该角色的数据库。在admin
数据库上创建的角色可以包含适用于所有数据库或集群的权限。
必需的访问权限
您必须对权限的目标数据库执行 grantRole
操作才能授予该权限。要授予对多个数据库或 cluster
资源的权限,必须对 admin
数据库执行 grantRole
操作。
例子
以下grantPrivilegesToRole
命令向products
数据库中存在的service
角色授予另外两个特权:
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
数据库中搜索所有非系统collection。该权限不允许对collection(例如system.js
collection)进行查询。要授予对这些collection的访问权限,请在privileges
数组中显式预配访问权限。请参阅资源文档。