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

grantPrivilegesToRole(数据库命令)

grantPrivilegesToRole

为运行命令的数据库上定义的 用户定义 角色分配其他 权限 。

提示

In mongosh, this command can also be run through the db.grantPrivilegesToRole() helper method.

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.

The grantPrivilegesToRole command uses the following syntax:

db.runCommand(
{
grantPrivilegesToRole: "<role>",
privileges: [
{
resource: { <resource> }, actions: [ "<action>", ... ]
},
...
],
writeConcern: { <write concern> },
comment: <any>
}
)

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

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

重要

This command is not supported in M0 and Flex clusters. For more information, see Unsupported Commands.

该命令具有以下字段:

字段
类型
说明

grantPrivilegesToRole

字符串

要授予权限的用户定义角色的名称。

privileges

阵列

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

writeConcern

文档

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

comment

any

可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:

注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。

角色的权限适用于创建该角色的数据库。在admin数据库上创建的角色可以包含适用于所有数据库或集群的权限。

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

privileges大量中的第一个权限允许用户搜索products数据库中的所有非系统集合。 该权限不允许对系统集合进行查询,例如system.js集合。 要授予访问权限这些系统集合的访问权限,请在privileges大量中显式预配访问权限。 请参阅有关自管理部署的资源文档。

第二个特权明确允许对所有数据库上的 集合执行find system.js操作。