db.grantPrivilegesToRole()

Definition

  • db.grantPrivilegesToRole(rolename, privileges, writeConcern)
  • Grants additional privileges to a user-defined role.

The grantPrivilegesToRole() method uses the following syntax:

  1. db.grantPrivilegesToRole(
  2. "< rolename >",
  3. [
  4. { resource: { <resource> }, actions: [ "<action>", ... ] },
  5. ...
  6. ],
  7. { < writeConcern > }
  8. )

The grantPrivilegesToRole() method takes the following arguments:

ParameterTypeDescriptionrolenamestringThe name of the role to grant privileges to.privilegesarrayThe privileges to add to the role. For the format of a privilege, seeprivileges.writeConcerndocumentOptional. The level of write concern for themodification. The writeConcern document takes the samefields as the getLastError command.

The grantPrivilegesToRole() method can grant one or moreprivileges. Each <privilege> has the following syntax:

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

The db.grantPrivilegesToRole() method wraps thegrantPrivilegesToRole command.

Behavior

Replica set

If run on a replica set, db.grantPrivilegesToRole() is executed using majority write concern by default.

Scope

Except for roles created in the admin database, a role can onlyinclude privileges that apply to its database

A role created in the admin database can include privileges thatapply to the admin database, other databases or to thecluster resource.

Required Access

You must have the grantRoleaction on the database a privilege targets in order togrant the privilege. To grant a privilege on multiple databases or on thecluster resource, you must have the grantRole action onthe admin database.

Example

The following db.grantPrivilegesToRole() operation grants twoadditional privileges to the role inventoryCntrl01, which exists on theproducts database. The operation is run on that database:

  1. use products
  2. db.grantPrivilegesToRole(
  3. "inventoryCntrl01",
  4. [
  5. {
  6. resource: { db: "products", collection: "" },
  7. actions: [ "insert" ]
  8. },
  9. {
  10. resource: { db: "products", collection: "system.js" },
  11. actions: [ "find" ]
  12. }
  13. ],
  14. { w: "majority" }
  15. )

The first privilege permits users with this role to perform theinsert action on all collections ofthe products database, except the system collections. To access a system collection, aprivilege must explicitly specify the system collection in the resourcedocument, as in the second privilege.

The second privilege permits users with this role to perform thefindaction on theproduct database’s system collection named system.js.