Bird
Raised Fist0
MongoDBquery~15 mins

Custom role creation in MongoDB - Deep Dive

Choose your learning style10 modes available
Overview - Custom role creation
What is it?
Custom role creation in MongoDB means making your own set of permissions to control what users can do. Instead of using built-in roles, you define exactly which actions are allowed on which resources. This helps tailor security to your application's needs. It is done by specifying privileges and roles in a role document.
Why it matters
Without custom roles, you must rely on predefined roles that might give too many or too few permissions. This can lead to security risks or hinder productivity. Custom roles let you follow the principle of least privilege, giving users only what they need. This protects your data and helps meet compliance requirements.
Where it fits
Before learning custom role creation, you should understand MongoDB basics, user authentication, and built-in roles. After mastering custom roles, you can explore advanced security topics like auditing, encryption, and role-based access control (RBAC) best practices.
Mental Model
Core Idea
A custom role in MongoDB is a tailored permission set that defines exactly what actions a user can perform on specific database resources.
Think of it like...
Creating a custom role is like making a personalized keyring with keys only for the doors you want someone to open, instead of giving them a master key to the whole building.
┌─────────────────────────────┐
│        Custom Role          │
├─────────────┬───────────────┤
│ Privileges  │ Resources     │
│ - action 1  │ - database 1  │
│ - action 2  │ - collectionA │
│ ...         │ ...           │
└─────────────┴───────────────┘
        ↓
┌─────────────────────────────┐
│       Assigned to User       │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding MongoDB Roles
🤔
Concept: Learn what roles are and how they control access in MongoDB.
MongoDB uses roles to manage permissions. Each role has privileges that allow actions like reading or writing data. Built-in roles cover common needs, like 'read' or 'dbAdmin'. Roles are assigned to users to control what they can do.
Result
You understand that roles are sets of permissions assigned to users to control database access.
Knowing roles are collections of permissions helps you see why customizing them can improve security.
2
FoundationBasics of Privileges and Actions
🤔
Concept: Privileges define what actions can be done on which resources.
A privilege has two parts: an action and a resource. Actions are operations like 'find', 'insert', or 'dropCollection'. Resources specify where the action applies, such as a database or collection. Together, they form the building blocks of roles.
Result
You can identify what actions and resources make up a privilege.
Understanding privileges as action-resource pairs clarifies how roles control specific operations.
3
IntermediateCreating a Simple Custom Role
🤔Before reading on: do you think you can create a role that only allows reading from one collection? Commit to your answer.
Concept: Learn how to define a custom role with specific privileges using the createRole command.
To create a custom role, use the db.createRole() method. You specify the role name, the privileges (actions and resources), and optionally inherited roles. For example, a role that allows only 'find' on 'mydb.mycollection' looks like this: { role: 'readMyCollection', privileges: [ { resource: { db: 'mydb', collection: 'mycollection' }, actions: ['find'] } ], roles: [] } This role can then be assigned to users.
Result
A new role exists that restricts users to reading only one collection.
Knowing how to create a role with precise privileges lets you enforce fine-grained access control.
4
IntermediateAssigning Custom Roles to Users
🤔Before reading on: do you think assigning a custom role to a user is different from assigning a built-in role? Commit to your answer.
Concept: Learn how to assign your custom role to a user to grant permissions.
After creating a custom role, assign it to a user with db.grantRolesToUser(). For example: use admin db.grantRolesToUser('alice', [{ role: 'readMyCollection', db: 'admin' }]) This gives user 'alice' the permissions defined in 'readMyCollection'.
Result
User 'alice' can now perform only the actions allowed by the custom role.
Understanding role assignment shows how permissions flow from roles to users.
5
IntermediateCombining Custom and Built-in Roles
🤔Before reading on: do you think a user can have multiple roles with combined permissions? Commit to your answer.
Concept: Users can have multiple roles, and permissions combine to allow more actions.
You can assign multiple roles to a user, including built-in and custom roles. MongoDB merges all privileges from assigned roles. For example, a user can have 'read' on one database and a custom role for admin tasks on another. This flexibility helps tailor access.
Result
Users can have a mix of permissions from different roles.
Knowing that roles combine helps design layered security with minimal privilege overlap.
6
AdvancedUsing Inherited Roles in Custom Roles
🤔Before reading on: do you think custom roles can include other roles inside them? Commit to your answer.
Concept: Custom roles can inherit privileges from other roles to avoid repetition.
When creating a custom role, you can specify existing roles in the 'roles' array. This means your custom role includes all privileges from those roles plus any new privileges you add. For example: { role: 'customAdmin', privileges: [ ... ], roles: [{ role: 'readWrite', db: 'admin' }] } This role has all 'readWrite' privileges plus custom ones.
Result
Custom roles can build on existing roles, making management easier.
Understanding inheritance reduces duplication and simplifies role maintenance.
7
ExpertSecurity Implications and Best Practices
🤔Before reading on: do you think giving broad privileges in custom roles is safe? Commit to your answer.
Concept: Learn how to design custom roles securely and avoid common pitfalls.
Custom roles should follow the principle of least privilege: grant only necessary actions on needed resources. Avoid using 'anyResource' or broad actions like 'dropDatabase' unless absolutely required. Regularly audit roles and user assignments. Use role inheritance carefully to prevent privilege escalation. Also, understand that some actions require cluster-level privileges, which need special handling.
Result
You can create secure custom roles that protect your data and comply with policies.
Knowing security best practices prevents accidental data exposure and strengthens your MongoDB deployment.
Under the Hood
MongoDB stores role definitions in the admin database's system.roles collection. When a user authenticates, MongoDB merges all privileges from assigned roles into an effective permission set. Each privilege is an action-resource pair checked at runtime before allowing operations. This check happens inside the database engine, ensuring only authorized actions proceed.
Why designed this way?
MongoDB's role-based access control was designed to be flexible and extensible. Built-in roles cover common cases, but custom roles allow fine-tuning for diverse applications. Storing roles as documents allows easy updates and inheritance. The action-resource model balances granularity and simplicity, avoiding overly complex permission systems.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│  Role Docs    │──────▶│ Privilege Set │──────▶│ Permission    │
│ (system.roles)│       │ (actions +    │       │ Check at      │
│               │       │  resources)   │       │ Runtime       │
└───────────────┘       └───────────────┘       └───────────────┘
         ▲                      ▲                      ▲
         │                      │                      │
         │                      │                      │
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ User Assigned │──────▶│ Role Merging  │──────▶│ Effective     │
│ Roles        │       │ (combine all) │       │ Permissions   │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think a custom role automatically grants all privileges of the roles it inherits? Commit yes or no.
Common Belief:A custom role that inherits other roles replaces those roles' privileges with its own privileges.
Tap to reveal reality
Reality:A custom role that inherits other roles combines its own privileges with all privileges from the inherited roles.
Why it matters:Misunderstanding inheritance can lead to unexpected permissions, causing security holes or access issues.
Quick: Do you think assigning a custom role to a user immediately grants cluster-wide admin rights? Commit yes or no.
Common Belief:Any custom role can grant cluster-wide admin rights if assigned to a user.
Tap to reveal reality
Reality:Custom roles only grant cluster-wide rights if explicitly given cluster-level privileges; otherwise, they are limited to specified databases or collections.
Why it matters:Assuming all custom roles are powerful can cause over-trusting users or misconfiguring security.
Quick: Do you think you can create a custom role without specifying any privileges? Commit yes or no.
Common Belief:A custom role can be created without privileges and still grant access.
Tap to reveal reality
Reality:A custom role without privileges grants no permissions unless it inherits roles that have privileges.
Why it matters:Creating empty roles expecting access leads to confusion and failed operations.
Quick: Do you think MongoDB roles control network access to the database? Commit yes or no.
Common Belief:MongoDB roles control who can connect to the database server over the network.
Tap to reveal reality
Reality:MongoDB roles control what authenticated users can do inside the database, not network-level access, which is managed separately.
Why it matters:Confusing network access with role permissions can cause security gaps or misconfigured firewalls.
Expert Zone
1
Custom roles can include privileges that affect cluster-wide resources, but these require careful assignment to avoid privilege escalation.
2
Role inheritance merges privileges but does not override; conflicts are additive, which can unintentionally broaden access.
3
Some actions require multiple privileges or specific resource scopes, so partial privileges may not work as expected.
When NOT to use
Avoid custom roles when simple built-in roles suffice, as custom roles add complexity and maintenance overhead. For very dynamic or temporary permissions, consider using MongoDB's temporary roles or external access control systems.
Production Patterns
In production, teams create layered roles: base roles for common permissions, custom roles for project-specific needs, and audit roles for monitoring. Roles are version-controlled and reviewed regularly. Automation scripts manage role creation and assignment to ensure consistency.
Connections
Role-Based Access Control (RBAC)
Custom role creation in MongoDB is a specific implementation of RBAC principles.
Understanding RBAC helps grasp why MongoDB separates privileges into roles and assigns them to users for scalable security.
Operating System User Permissions
Both MongoDB custom roles and OS user permissions control access to resources using roles and privileges.
Knowing OS permissions clarifies how MongoDB roles similarly restrict actions, reinforcing the principle of least privilege.
Security Policy Design
Custom role creation builds on security policy design concepts like least privilege and separation of duties.
Learning security policy design outside databases helps create safer, more maintainable MongoDB roles.
Common Pitfalls
#1Granting overly broad privileges in a custom role.
Wrong approach:db.createRole({ role: 'allAccess', privileges: [{ resource: { anyResource: true }, actions: ['anyAction'] }], roles: [] })
Correct approach:db.createRole({ role: 'readOnly', privileges: [{ resource: { db: 'mydb', collection: '' }, actions: ['find'] }], roles: [] })
Root cause:Misunderstanding the scope of 'anyResource' and 'anyAction' leads to excessive permissions.
#2Creating a custom role without specifying any privileges or inherited roles.
Wrong approach:db.createRole({ role: 'emptyRole', privileges: [], roles: [] })
Correct approach:db.createRole({ role: 'readRole', privileges: [{ resource: { db: 'mydb', collection: '' }, actions: ['find'] }], roles: [] })
Root cause:Assuming a role exists without privileges grants access, but it actually grants none.
#3Assigning a custom role to a user without specifying the correct database for the role.
Wrong approach:db.grantRolesToUser('bob', [{ role: 'readMyCollection', db: 'wrongDB' }])
Correct approach:db.grantRolesToUser('bob', [{ role: 'readMyCollection', db: 'admin' }])
Root cause:Confusing the database where the role is defined with the database where the user exists causes assignment failure.
Key Takeaways
Custom roles in MongoDB let you define precise permissions by specifying actions on resources.
Roles are collections of privileges that can inherit from other roles, combining permissions.
Assigning roles to users controls what they can do inside the database, enforcing security.
Following least privilege and auditing roles regularly prevents security risks.
Understanding role inheritance and privilege scope is key to avoiding unintended access.

Practice

(1/5)
1. What is the main purpose of creating a custom role in MongoDB?
easy
A. To speed up database queries
B. To assign specific permissions tailored to user needs
C. To backup the database automatically
D. To create new collections in the database

Solution

  1. Step 1: Understand role purpose

    Custom roles are designed to control what actions a user can perform.
  2. Step 2: Match purpose to options

    Only To assign specific permissions tailored to user needs describes assigning specific permissions tailored to user needs.
  3. Final Answer:

    To assign specific permissions tailored to user needs -> Option B
  4. Quick Check:

    Custom role purpose = Assign specific permissions [OK]
Hint: Custom roles control user permissions precisely [OK]
Common Mistakes:
  • Confusing roles with database backups
  • Thinking roles speed up queries
  • Assuming roles create collections
2. Which of the following is the correct syntax to create a custom role named readWriteReports with read and write privileges on the reports database?
easy
A. db.createRole({role: "readWriteReports", privileges: [{resource: {db: "reports"}, actions: ["readWrite"]}], roles: []})
B. db.createRole({role: "readWriteReports", privileges: [{resource: {db: "reports", collection: ""}, actions: ["find", "insert", "update"]}], roles: []})
C. db.createRole({name: "readWriteReports", privileges: [{resource: {db: "reports", collection: ""}, actions: ["find", "insert", "update"]}], roles: []})
D. db.createRole({name: "readWriteReports", privileges: [{resource: {db: "reports"}, actions: ["readWrite"]}], roles: []})

Solution

  1. Step 1: Check correct field names

    The field for role name is name, not role.
  2. Step 2: Verify privileges structure

    Privileges must specify resource with db and collection, and actions as an array of strings.
  3. Final Answer:

    db.createRole({name: "readWriteReports", privileges: [{resource: {db: "reports", collection: ""}, actions: ["find", "insert", "update"]}], roles: []}) -> Option C
  4. Quick Check:

    Use 'name' for role name and specify privileges correctly [OK]
Hint: Use 'name' key for role name in createRole [OK]
Common Mistakes:
  • Using 'role' instead of 'name' for role name
  • Omitting collection field in resource
  • Using 'readWrite' as action instead of specific actions
3. Given the following command, what will be the effect of the custom role limitedUser?
db.createRole({
  name: "limitedUser",
  privileges: [
    { resource: { db: "sales", collection: "orders" }, actions: ["find"] }
  ],
  roles: []
})
medium
A. User has no permissions on sales.orders collection
B. User can read and write on sales.orders collection
C. User can perform any action on sales database
D. User can only read documents from sales.orders collection

Solution

  1. Step 1: Analyze privileges actions

    The action specified is only "find", which means read access.
  2. Step 2: Understand resource scope

    The resource is the "orders" collection in the "sales" database, so permissions apply only there.
  3. Final Answer:

    User can only read documents from sales.orders collection -> Option D
  4. Quick Check:

    Action 'find' = read only on specified collection [OK]
Hint: Action 'find' means read-only permission [OK]
Common Mistakes:
  • Assuming 'find' allows write operations
  • Thinking permissions apply to whole database
  • Confusing empty roles array as full access
4. Identify the error in this custom role creation command:
db.createRole({
  name: "dataEditor",
  privileges: [
    { resource: { db: "analytics", collection: "reports" }, actions: "update" }
  ],
  roles: []
})
medium
A. The 'actions' field should be an array, not a string
B. The 'resource' field is missing the database name
C. The 'name' field should be 'role'
D. The 'roles' array cannot be empty

Solution

  1. Step 1: Check 'actions' field type

    The 'actions' field must be an array of strings, but here it is a single string "update".
  2. Step 2: Verify other fields

    The 'resource' includes both db and collection correctly; 'name' is correct; 'roles' can be empty.
  3. Final Answer:

    The 'actions' field should be an array, not a string -> Option A
  4. Quick Check:

    'actions' must be an array [OK]
Hint: Always use array for 'actions' even if one action [OK]
Common Mistakes:
  • Using string instead of array for 'actions'
  • Confusing 'name' with 'role' field
  • Thinking 'roles' array cannot be empty
5. You want to create a custom role reportManager that allows users to read all collections in the reports database and also run the aggregate action on the summary collection only. Which of the following commands correctly implements this?
hard
A. db.createRole({name: "reportManager", privileges: [{resource: {db: "reports", collection: ""}, actions: ["find"]}, {resource: {db: "reports", collection: "summary"}, actions: ["aggregate"]}], roles: []})
B. db.createRole({name: "reportManager", privileges: [{resource: {db: "reports"}, actions: ["find"]}, {resource: {db: "reports", collection: "summary"}, actions: ["aggregate"]}], roles: []})
C. db.createRole({name: "reportManager", privileges: [{resource: {db: "reports", collection: "summary"}, actions: ["find", "aggregate"]}], roles: []})
D. db.createRole({name: "reportManager", privileges: [{resource: {db: "reports", collection: ""}, actions: ["find", "aggregate"]}], roles: []})

Solution

  1. Step 1: Understand the requirements

    Users must have read (find) access on all collections in 'reports' and aggregate only on 'summary' collection.
  2. Step 2: Check privileges for all collections

    Using collection: "" means all collections in the database, so first privilege grants find on all collections.
  3. Step 3: Check aggregate privilege on summary

    Second privilege grants aggregate only on 'summary' collection.
  4. Final Answer:

    db.createRole({name: "reportManager", privileges: [{resource: {db: "reports", collection: ""}, actions: ["find"]}, {resource: {db: "reports", collection: "summary"}, actions: ["aggregate"]}], roles: []}) -> Option A
  5. Quick Check:

    Separate privileges for all collections and specific collection actions [OK]
Hint: Use empty string for all collections, specify collection for specific actions [OK]
Common Mistakes:
  • Using db only without collection for find
  • Combining find and aggregate on all collections
  • Missing separate privilege for aggregate on summary
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard