db.grantRolesToUser()

Definition

  • db.grantRolesToUser(username, roles, writeConcern)
  • Grants additional roles to a user.

The grantRolesToUser method uses the following syntax:

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

The grantRolesToUser method takes the following arguments:

ParameterTypeDescriptionuserstringThe name of the user to whom to grant roles.rolesarrayAn array of additional roles to grant to the user.writeConcerndocumentOptional. The level of write concern for themodification. The writeConcern document takes the samefields as the getLastError command.

In the roles field, you can specify bothbuilt-in roles and user-definedroles.

To specify a role that exists in the same database wheredb.grantRolesToUser() runs, you can either specify the role with the name ofthe role:

  1. "readWrite"

Or you can specify the role with a document, as in:

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

To specify a role that exists in a different database, specify the rolewith a document.

The db.grantRolesToUser() method wraps thegrantRolesToUser command.

Behavior

Replica set

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

Required Access

You must have the grantRoleaction on a database to grant a role on that database.

Example

Given a user accountUser01 in the products database with the followingroles:

  1. "roles" : [
  2. { "role" : "assetsReader",
  3. "db" : "assets"
  4. }
  5. ]

The following grantRolesToUser() operation gives accountUser01the readWrite role on the products database and theread role on the stock database.

  1. use products
  2. db.grantRolesToUser(
  3. "accountUser01",
  4. [ "readWrite" , { role: "read", db: "stock" } ],
  5. { w: "majority" , wtimeout: 4000 }
  6. )

The user accountUser01 in the products database now has the followingroles:

  1. "roles" : [
  2. { "role" : "assetsReader",
  3. "db" : "assets"
  4. },
  5. { "role" : "read",
  6. "db" : "stock"
  7. },
  8. { "role" : "readWrite",
  9. "db" : "products"
  10. }
  11. ]