db.grantRolesToUser()

在本页面

Definition

grantRolesToUser方法使用以下语法:

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

grantRolesToUser方法采用以下参数:

Parameter Type Description
user string 要授予角色的用户的名称。
roles array 授予用户的一系列其他角色。
writeConcern document 可选的。修改的write concern级别。 writeConcern文档具有与getLastError命令相同的字段。

roles字段中,您可以同时指定built-in rolesuser-defined roles

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

"readWrite"

或者,您可以通过文档指定角色,如:

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

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

db.grantRolesToUser()方法包装grantRolesToUser命令。

Behavior

Replica set

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

Required Access

您必须在数据库上拥有grantRole action才能在该数据库上授予角色。

Example

products数据库中为用户accountUser01提供以下角色:

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

以下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"
    }
]
首页