db.grantPrivilegesToRole()

在本页面

Definition

grantPrivilegesToRole()方法使用以下语法:

db.grantPrivilegesToRole(
    "< rolename >",
    [
        { resource: { <resource> }, actions: [ "<action>", ... ] },
        ...
    ],
    { < writeConcern > }
)

grantPrivilegesToRole()方法采用以下参数:

Parameter Type Description
rolename string 授予特权的角色名称。
privileges array 添加到角色的特权。有关特权的格式,请参见privileges
writeConcern document 可选的。修改的write concern级别。 writeConcern文档具有与getLastError命令相同的字段。

grantPrivilegesToRole()方法可以授予一个或多个特权。每个<privilege>的语法如下:

{ resource: { <resource> }, actions: [ "<action>", ... ] }

db.grantPrivilegesToRole()方法包装grantPrivilegesToRole命令。

Behavior

Replica set

如果在副本集上运行,默认情况下将使用majority写关注来执行db.grantPrivilegesToRole()

Scope

除在admin数据库中创建的角色外,角色只能包含适用于其数据库的特权

admin数据库中创建的角色可以包括适用于admin数据库,其他数据库或cluster资源的特权。

Required Access

您必须在数据库上具有grantRole action的特权目标才能授予该特权。要在多个数据库或cluster资源上授予特权,您必须对admin数据库具有grantRole操作。

Example

以下db.grantPrivilegesToRole()操作向products数据库中存在的角色inventoryCntrl01授予了两个附加特权。该操作在该数据库上运行:

use products
db.grantPrivilegesToRole(
  "inventoryCntrl01",
  [
    {
      resource: { db: "products", collection: "" },
      actions: [ "insert" ]
    },
    {
      resource: { db: "products", collection: "system.js" },
      actions: [ "find" ]
    }
  ],
  { w: "majority" }
)

第一个特权允许具有此角色的用户对products数据库的所有集合(除了system collections)执行insert action。要访问系统集合,特权必须与第二个特权一样,在资源文档中显式指定系统集合。

第二种特权允许具有此角色的用户在名为system.jsproduct数据库的系统集合上执行find action

首页