对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

db.grantPrivilegesToRole()(mongosh方法)

db.grantPrivilegesToRole(rolename, privileges, writeConcern)

用户定义的角色授予的其他权限

重要

mongosh 方法

This page documents a mongosh method. 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 对所有命令的支持的信息,请参阅不支持的命令

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 操作系统集合除外。要访问系统集合,权限必须在资源文档中显式指定系统集合,如第二个权限所示。

第二个权限允许具有此角色的用户对名为 system.jsproduct 数据库系统集合执行find操作