grantPrivilegesToRole

Definition

  1. {
  2. grantPrivilegesToRole: "<role>",
  3. privileges: [
  4. {
  5. resource: { <resource> }, actions: [ "<action>", ... ]
  6. },
  7. ...
  8. ],
  9. writeConcern: { <write concern> }
  10. }

The grantPrivilegesToRole command has the followingfields:

FieldTypeDescriptiongrantPrivilegesToRolestringThe name of the user-defined 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.

Behavior

A role’s privileges apply to the database where the role is created. Arole created on the admin database can include privileges that applyto all databases or to the cluster.

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 grantPrivilegesToRole command grants twoadditional privileges to the service role that exists in theproducts database:

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

The first privilege in the privileges array allows the user tosearch on all non-system collections in the products database. Theprivilege does not allow queries on system collections, such as the system.js collection. To grant access to thesesystem collections, explicitly provision access in the privilegesarray. See Resource Document.

The second privilege explicitly allows the find action onsystem.js collections on alldatabases.