Docs 菜单

Docs 主页开发应用程序MongoDB Manual

db.grantRolesToUser()

在此页面上

  • 定义
  • 行为
  • 必需的访问权限
  • 例子
db.grantRolesToUser(username, roles, writeConcern)

授予用户其他角色。

重要

mongosh 方法

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

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

对于 MongoDB API 驱动程序,请参阅特定语言的MongoDB 驱动程序文档。

对于传统 mongo Shell 文档,请参阅相应 MongoDB Server 版本的文档:

mongo shell v4.4

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

db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )

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

范围
类型
说明
user
字符串
要向其授予角色的用户的名称。
roles
阵列
授予用户的附加角色的数组。
writeConcern
文档

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

roles 字段中,可以指定内置角色用户自定义角色

要指定运行db.grantRolesToUser()的同一数据库中存在的角色,可以使用角色名称指定该角色:

"readWrite"

或者,可以使用文档指定角色,如下所示:

{ role: "<role>", db: "<database>" }

要指定存在于其他数据库中的角色,请使用文档指定该角色。

db.grantRolesToUser()方法封装了grantRolesToUser命令。

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

必须对数据库执行 grantRole 操作才能在该数据库上授予角色。

假设 products 数据库中有一个具有以下角色的用户 accountUser01

"roles" : [
{ "role" : "assetsReader",
"db" : "assets"
}
]

以下db.grantRolesToUser()操作为accountUser01赋予了products数据库上的readWrite角色以及stock数据库上的read角色。

use products
db.grantRolesToUser(
"accountUser01",
[ "readWrite" , { role: "read", db: "stock" } ],
{ w: "majority" , wtimeout: 4000 }
)

products 数据库中的用户 accountUser01 现在具有以下角色:

"roles" : [
{ "role" : "assetsReader",
"db" : "assets"
},
{ "role" : "read",
"db" : "stock"
},
{ "role" : "readWrite",
"db" : "products"
}
]
← db.getUsers()