定义
db.grantPrivilegesToRole(rolename, privileges, writeConcern)重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for database commands or language-specific drivers, such as Node.js.有关数据库命令,请参阅
grantPrivilegesToRole命令。如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
The
db.grantPrivilegesToRole()method uses the following syntax:db.grantPrivilegesToRole( "< rolename >", [ { resource: { <resource> }, actions: [ "<action>", ... ] }, ... ], { < writeConcern > } ) The
db.grantPrivilegesToRole()method takes the following arguments:Parameter类型说明rolename字符串
要授予权限的角色名称。
privileges阵列
要添加到角色的权限。有关权限的格式,请参阅
privileges。writeConcern文档
The
db.grantPrivilegesToRole()method can grant one or more privileges. Each<privilege>has the following syntax:{ resource: { <resource> }, actions: [ "<action>", ... ] }
兼容性
此方法可用于以下环境中托管的部署:
重要
MongoDB Atlas 集群不支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
副本集
If run on a replica set, db.grantPrivilegesToRole() is executed using "majority" write concern by default.
范围
除了在 admin 数据库中创建的角色之外,角色只能包含适用于其数据库的权限
在 admin 数据库中创建的角色可包含适用于 admin 数据库、其他数据库或集群资源的权限。
特权
当您指定privileges 大量时,可以指定要应用数据库中的多个集合或整个数据库的权限。
以下语法指定对 products数据库中多个集合的权限。
privileges: [ { resource: { db: 'products', collection: 'coll1' }, actions: [ 'bypassDocumentValidation' ] }, { resource: { db: 'products', collection: 'coll2' }, actions: [ 'bypassDocumentValidation' ] } ]
以下语法指定对 products数据库中所有集合的权限。
privileges: [ { resource: { db: 'products', collection: '' }, actions: [ 'bypassDocumentValidation' ] } ]
必需的访问权限
您必须对权限的目标数据库执行 grantRole 操作才能授予该权限。要授予对多个数据库或 cluster 资源的权限,必须对 admin 数据库执行 grantRole 操作。
例子
The following db.grantPrivilegesToRole() operation grants two additional privileges to the role inventoryCntrl01, which exists on the products database. The operation is run on that database:
use products db.grantPrivilegesToRole( "inventoryCntrl01", [ { resource: { db: "products", collection: "" }, actions: [ "insert" ] }, { resource: { db: "products", collection: "system.js" }, actions: [ "find" ] } ], { w: "majority" } )
第一个权限允许具有此角色的用户对 products 数据库的所有集合执行 insert 操作,系统集合除外。要访问系统集合,权限必须在资源文档中显式指定系统集合,如第二个权限所示。