Docs 菜单

db.grantPrivilegesToRole()

db.grantPrivilegesToRole(rolename, privileges, writeConcern)

Grants additional privileges to a user-defined role.

重要

mongosh 方法

本页面提供 mongosh 方法的相关信息。这不是数据库命令或特定语言驱动程序(例如 Node.js)的相关文档。

有关数据库命令,请参阅 grantPrivilegesToRole 命令。

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.

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

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

db.grantPrivilegesToRole() 方法接受以下参数:

Parameter
类型
说明

rolename

字符串

The name of the role to grant privileges to.

privileges

阵列

The privileges to add to the role. For the format of a privilege, see privileges.

writeConcern

文档

可选。操作的写关注级别。请参阅写关注规范

The db.grantPrivilegesToRole() method can grant one or more privileges. Each <privilege> has the following syntax:

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

此方法可用于以下环境中托管的部署:

重要

This command is not supported in MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.

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

Except for roles created in the admin database, a role can only include privileges that apply to its database

A role created in the admin database can include privileges that apply to the admin database, other databases or to the 集群 resource.

您必须对权限的目标数据库执行 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" }
)

The first privilege permits users with this role to perform the insert 操作 on all collections of the products database, except the system collections. To access a system collection, a privilege must explicitly specify the system collection in the resource document, as in the second privilege.

The second privilege permits users with this role to perform the find 操作 on the product database's system collection named system.js.