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

db.grantPrivilegesToRole()(mongosh方法)

db.grantPrivilegesToRole(rolename, privileges, writeConcern)

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

重要

mongosh 方法

本页介绍了mongosh 方法。这不是数据库命令或特定语言驱动程序(例如 Node.js)的文档。

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

如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。

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

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

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

Parameter
类型
说明

rolename

字符串

要授予权限的角色名称。

privileges

阵列

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

writeConcern

文档

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

db.grantPrivilegesToRole()方法可以授予一项或多项权限。每个<privilege> 都具有以下事务语法:

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

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

重要

MongoDB Atlas 集群不支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令

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

除了在 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 操作。

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

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操作