Configure RoleBased Access Control in MongoDB (original) (raw)

Last Updated : 20 Apr, 2026

MongoDB secures database access using authentication mechanisms and role-based access control (RBAC) to ensure only authorized users can access and modify data.

Role-Based Access Control (RBAC)

MongoDB uses RBAC to authorize authenticated users with specific permissions on databases and collections, ensuring controlled access to resources.

role_based_access_control_

Understanding RBAC in MongoDB

Built-In Roles in MongoDB

MongoDB provides several built-in roles to cater to different administrative and operational tasks. Some of the key built-in roles include:

Database Administration Roles

Cluster Administration Roles

Backup and Restoration Roles

Superuser Roles:

Creating a User-Defined Role

Define custom roles to grant fine-grained permissions for specific actions and resources in MongoDB.

**1. Define the role

Decide the permissions the role should have, such as read or write access to specific databases or collections.

use myDatabase

db.createRole({
role: "customRole",
privileges: [
{ resource: { db: "myDatabase", collection: "" }, actions: ["find", "insert"] }
],
roles: []
})

**2. Assign the Role

Assign the role to a user using the db.grantRolesToUser() method. For example:

db.grantRolesToUser("myUser", ["customRole"])

Modify Access for an Existing User

To modify access for an existing user in MongoDB Here's a step-by-step explanation with examples:

**1. List Existing Roles

Use db.getUser() to view the roles assigned to the user.

db.getUser("myUser")

**2. Modify Roles

Use db.grantRolesToUser() to add roles and db.revokeRolesFromUser() to remove roles.

db.grantRolesToUser("myUser", ["customRole"])

**3. Verify Changes

Verify the updates by listing the user’s roles again.

db.revokeRolesFromUser("myUser", ["customRole"])

Connect to MongoDB with Appropriate Privileges

Connect to MongoDB using a user account with the required roles to ensure authorized access to databases and operations.

**1. Start MongoDB Shell

Start the MongoDB shell by running the following command in your terminal:

mongo -u "adminUser" -p "strongPassword" --authenticationDatabase "admin"

**2. Authenticate

(If not already authenticated) authenticate with a user that has the required privileges:

use admin;
db.auth("adminUser", "strongPassword");

**3. Connect to Database

Switch to the desired database using the use command.

use myDatabase

**4. Verify Access

Verify permissions by performing an operation such as querying documents:

db.collection.find();