Docs 菜单

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>
}
)

此命令可用于以下环境中托管的部署:

重要

M 0 、M 2和 M 5集群不支持此命令。 有关更多信息,请参阅不支持的命令。

该命令具有以下字段:

字段
类型
说明

grantPrivilegesToRole

字符串

The name of the user-defined role to grant privileges to.

privileges

阵列

要添加到角色的权限。有关权限的格式,请参阅 privileges

writeConcern

文档

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

comment

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.