Navigation
This version has reached end of life on October 2016. Learn more about upgrading your version of MongoDB.

Assign a User a Role

Changed in version 2.6.

Overview

A role provides a user privileges to perform a set of actions on a resource. A user can have multiple roles.

In MongoDB systems with authorization enforced, you must grant a user a role for the user to access a database resource. To assign a role, first determine the privileges the user needs and then determine the role that grants those privileges.

For an overview of roles and privileges, see Authorization. For descriptions of the access each built-in role provides, see the section on built-in roles.

Prerequisites

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

To view a role’s information, you must be explicitly granted the role or must have the viewRole action on the role’s database.

Procedure

1

Connect with the privilege to grant roles.

Connect to the mongod or mongos as a user with the privileges specified in the Prerequisites section.

The following procedure uses the siteUserAdmin created in Create a User Administrator.

mongo --port 27017 -u siteUserAdmin -p password --authenticationDatabase admin
2

Identify the user’s roles and privileges.

To display the roles and privileges of the user to be modified, use the db.getUser() and db.getRole() methods.

For example, to view roles for reportsUser created in Add a User to a Database, issue:

use reporting
db.getUser("reportsUser")

To display the privileges granted to the user by the readWrite role on the "accounts" database, issue:

use accounts
db.getRole( "readWrite", { showPrivileges: true } )
3

Identify the privileges to grant or revoke.

If the user requires additional privileges, grant to the user the role, or roles, with the required set of privileges. If such a role does not exist, create a new role with the appropriate set of privileges.

4

Grant a role to a user.

Grant the user the role using the db.grantRolesToUser() method.

For example, the following grants new roles to the user reportsUser created in Add a User to a Database.

use reporting
db.grantRolesToUser(
  "reportsUser",
  [
    { role: "readWrite", db: "products" } ,
    { role: "readAnyDatabase", db:"admin" }
  ]
)