Bird
Raised Fist0
MongoDBquery~15 mins

Built-in roles (read, readWrite, dbAdmin) in MongoDB - Deep Dive

Choose your learning style10 modes available
Overview - Built-in roles (read, readWrite, dbAdmin)
What is it?
Built-in roles in MongoDB are predefined sets of permissions that control what actions users can perform on the database. The roles read, readWrite, and dbAdmin each grant different levels of access to data and database management. These roles help manage security by limiting user capabilities to only what they need. They make it easier to assign permissions without creating custom rules from scratch.
Why it matters
Without built-in roles, database administrators would have to manually assign every permission to each user, which is time-consuming and error-prone. This could lead to security risks like unauthorized data changes or accidental deletions. Built-in roles provide a simple, reliable way to protect data and ensure users only do what they are allowed to do, keeping the database safe and organized.
Where it fits
Before learning about built-in roles, you should understand basic MongoDB concepts like databases, collections, and users. After this, you can learn about custom roles and advanced security features like authentication mechanisms and role-based access control (RBAC) policies.
Mental Model
Core Idea
Built-in roles are predefined permission sets that control what users can read, write, or manage in a MongoDB database.
Think of it like...
Think of built-in roles like job titles in a company: a 'Reader' can only read documents, a 'Writer' can both read and write, and a 'Manager' can also organize and maintain the workspace.
┌─────────────┐       ┌───────────────┐       ┌───────────────┐
│   read      │──────▶│  readWrite    │──────▶│    dbAdmin    │
│ (view only) │       │ (read + write)│       │ (manage db)   │
└─────────────┘       └───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding MongoDB Users
🤔
Concept: Users are accounts that connect to MongoDB and perform actions based on permissions.
In MongoDB, a user is created with a username and password. This user can be assigned roles that define what they can do. Without roles, users have no permissions and cannot access data or perform operations.
Result
Users exist but cannot read or write data until roles are assigned.
Knowing that users need roles to do anything helps understand why roles are essential for security.
2
FoundationWhat Are Roles in MongoDB?
🤔
Concept: Roles are collections of privileges that grant permissions to users.
A role bundles together specific actions like reading data, writing data, or managing the database. Assigning a role to a user gives them all the permissions in that role. MongoDB provides built-in roles to simplify this process.
Result
Users with roles can perform actions allowed by those roles.
Understanding roles as permission bundles clarifies how MongoDB controls user access efficiently.
3
IntermediateThe read Role: View-Only Access
🤔Before reading on: do you think a user with the read role can modify data? Commit to yes or no.
Concept: The read role allows users to view data but not change it.
Users with the read role can query and find documents in all collections of a database. They cannot insert, update, or delete any data. This role is useful for users who only need to analyze or report data.
Result
Users can see all data but cannot change anything.
Knowing that read role strictly limits users to viewing prevents accidental data changes by unauthorized users.
4
IntermediateThe readWrite Role: Modify Data Allowed
🤔Before reading on: does the readWrite role include database management permissions? Commit to yes or no.
Concept: The readWrite role allows users to read and modify data but not manage the database itself.
Users with readWrite can perform all read actions plus insert new documents, update existing ones, and delete documents in all collections of the database. However, they cannot create or drop collections or manage indexes.
Result
Users can fully work with data but cannot change database structure or settings.
Understanding the scope of readWrite helps assign appropriate permissions without risking structural changes.
5
IntermediateThe dbAdmin Role: Manage Database Structure
🤔Before reading on: can dbAdmin users read or write data by default? Commit to yes or no.
Concept: The dbAdmin role allows users to manage database structure but does not grant data read or write permissions by default.
Users with dbAdmin can create and drop collections, manage indexes, and view database statistics. They cannot read or modify the documents inside collections unless combined with read or readWrite roles.
Result
Users can organize and maintain the database but cannot access the data itself.
Knowing dbAdmin separates data access from database management helps design secure role combinations.
6
AdvancedCombining Roles for Flexible Permissions
🤔Before reading on: do you think assigning multiple roles to a user combines all their permissions? Commit to yes or no.
Concept: Users can have multiple roles, and their permissions add up to allow combined capabilities.
For example, assigning both readWrite and dbAdmin roles to a user lets them read, write data, and manage the database. MongoDB merges privileges from all assigned roles to determine what a user can do.
Result
Users gain all permissions from all their roles combined.
Understanding role combination allows precise control over user capabilities without creating custom roles.
7
ExpertRole Privileges and Inheritance Details
🤔Before reading on: do built-in roles inherit permissions from other roles internally? Commit to yes or no.
Concept: Built-in roles are defined with specific privileges and do not inherit from each other, but their privileges may overlap.
Each built-in role explicitly lists the actions it allows. For example, readWrite includes all read privileges plus write privileges but does not inherit from read. This explicit definition avoids confusion and makes permission checks efficient.
Result
Role privileges are clear and precise, avoiding hidden permissions.
Knowing roles do not inherit but overlap clarifies how MongoDB evaluates permissions and prevents unexpected access.
Under the Hood
MongoDB stores roles as documents defining allowed actions on resources like collections or databases. When a user attempts an operation, MongoDB checks the user's assigned roles and their privileges to decide if the action is permitted. This check happens at runtime for every operation, ensuring security is enforced consistently.
Why designed this way?
Explicit role definitions without inheritance simplify permission evaluation and reduce errors. Built-in roles cover common use cases, so administrators don't need to create custom roles for typical scenarios, speeding up setup and reducing mistakes.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   User Login  │──────▶│ Role Privileges│──────▶│ Permission    │
│ (username +   │       │ (read, write,  │       │ Check Engine  │
│  roles)       │       │  manage)       │       │ (allow/deny)  │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does the readWrite role automatically include dbAdmin privileges? Commit to yes or no.
Common Belief:readWrite role lets users manage the database structure like dbAdmin.
Tap to reveal reality
Reality:readWrite only allows reading and writing data, not managing collections or indexes.
Why it matters:Assuming readWrite includes dbAdmin can lead to security gaps where users cannot perform needed management tasks or mistakenly think they have those rights.
Quick: Can a user with only dbAdmin role read or modify documents? Commit to yes or no.
Common Belief:dbAdmin role includes full access to data since it manages the database.
Tap to reveal reality
Reality:dbAdmin only manages database structure; it does not grant read or write access to documents.
Why it matters:Misunderstanding this can cause confusion when users cannot access data despite having dbAdmin role.
Quick: If a user has both read and readWrite roles, do they have fewer permissions than just readWrite? Commit to yes or no.
Common Belief:Assigning multiple roles can restrict permissions to the lowest common set.
Tap to reveal reality
Reality:Permissions from all roles are combined, so the user has the union of all privileges.
Why it matters:Believing roles restrict each other can cause admins to under-assign permissions, blocking legitimate user actions.
Quick: Are built-in roles customizable by default? Commit to yes or no.
Common Belief:You can change what built-in roles do by editing them directly.
Tap to reveal reality
Reality:Built-in roles are fixed; to customize, you must create new roles based on them.
Why it matters:Trying to modify built-in roles directly wastes time and can cause confusion about permissions.
Expert Zone
1
Built-in roles are designed to be minimal and composable, encouraging combining roles rather than creating large monolithic roles.
2
The dbAdmin role includes privileges to run diagnostic commands, which can expose sensitive information if misused.
3
Role privileges are checked at the operation level, meaning some commands may require multiple privileges depending on their complexity.
When NOT to use
Built-in roles are not suitable when you need very fine-grained control over permissions, such as limiting access to specific collections or fields. In such cases, custom roles with tailored privileges should be used.
Production Patterns
In production, administrators often assign readWrite for application users who modify data, read for reporting users, and dbAdmin for maintenance staff. Roles are combined carefully to follow the principle of least privilege, minimizing security risks.
Connections
Role-Based Access Control (RBAC)
Built-in roles are a specific implementation of RBAC in MongoDB.
Understanding MongoDB roles helps grasp the broader security model of RBAC used in many systems to manage permissions efficiently.
Unix File Permissions
Both use predefined permission sets to control access to resources.
Knowing Unix permissions clarifies how roles group permissions to simplify user access management.
Organizational Job Roles
Built-in roles mirror job roles assigning responsibilities and limits.
Seeing roles as job titles helps understand why separating read, write, and admin tasks improves security and clarity.
Common Pitfalls
#1Assigning dbAdmin role expecting data read/write access.
Wrong approach:db.createUser({user: 'adminUser', pwd: 'pass', roles: [{role: 'dbAdmin', db: 'mydb'}]}) // Then trying to read data without read or readWrite role
Correct approach:db.createUser({user: 'adminUser', pwd: 'pass', roles: [{role: 'dbAdmin', db: 'mydb'}, {role: 'read', db: 'mydb'}]})
Root cause:Misunderstanding that dbAdmin does not include data access permissions.
#2Expecting readWrite role to allow creating indexes.
Wrong approach:db.createUser({user: 'writer', pwd: 'pass', roles: [{role: 'readWrite', db: 'mydb'}]}) // Then trying db.collection.createIndex({field: 1}) and failing
Correct approach:db.createUser({user: 'writer', pwd: 'pass', roles: [{role: 'readWrite', db: 'mydb'}, {role: 'dbAdmin', db: 'mydb'}]})
Root cause:Not knowing that index management requires dbAdmin privileges.
#3Trying to modify built-in roles directly.
Wrong approach:db.updateRole('read', {privileges: [...]}) // Attempt to change built-in role
Correct approach:db.createRole({role: 'customRead', privileges: [...], roles: ['read']})
Root cause:Believing built-in roles are editable instead of creating custom roles.
Key Takeaways
Built-in roles in MongoDB simplify permission management by grouping common privileges into read, readWrite, and dbAdmin roles.
The read role allows viewing data only, readWrite adds data modification, and dbAdmin manages database structure without data access.
Users can have multiple roles, and their permissions combine to grant all allowed actions.
Built-in roles are fixed and cannot be changed; for custom needs, create new roles based on them.
Understanding these roles helps secure MongoDB databases by assigning the least privilege necessary for each user.

Practice

(1/5)
1. Which built-in MongoDB role allows a user to only view data without making any changes?
easy
A. root
B. readWrite
C. dbAdmin
D. read

Solution

  1. Step 1: Understand the read role

    The read role allows users to view data but not modify it.
  2. Step 2: Compare with other roles

    readWrite allows changes, dbAdmin manages settings, root has full access.
  3. Final Answer:

    read -> Option D
  4. Quick Check:

    View-only permission = read [OK]
Hint: View-only means read role [OK]
Common Mistakes:
  • Confusing readWrite with read
  • Thinking dbAdmin allows data viewing only
  • Assuming root is for read-only
2. Which of the following is the correct way to assign the readWrite role to a user on the database mydb in MongoDB shell?
easy
A. db.grantRolesToUser('username', [{role: 'readWrite', db: 'mydb'}])
B. db.createUser({user: 'username', roles: ['readWrite']})
C. db.grantRolesToUser('username', ['readWrite'])
D. db.grantRolesToUser('username', [{role: 'readWrite', db: 'admin'}])

Solution

  1. Step 1: Check syntax for granting roles

    The correct syntax uses db.grantRolesToUser with an array of role objects specifying role and database.
  2. Step 2: Validate database name and role format

    db.grantRolesToUser('username', [{role: 'readWrite', db: 'mydb'}]) correctly specifies role as 'readWrite' and database as 'mydb'. db.grantRolesToUser('username', [{role: 'readWrite', db: 'admin'}]) wrongly uses 'admin' database.
  3. Final Answer:

    db.grantRolesToUser('username', [{role: 'readWrite', db: 'mydb'}]) -> Option A
  4. Quick Check:

    Grant role with role+db object array [OK]
Hint: Use role objects with db name in array for granting roles [OK]
Common Mistakes:
  • Passing roles as simple strings without db
  • Using wrong database name for the role
  • Using createUser instead of grantRolesToUser for existing users
3. Given a user with the dbAdmin role on database sales, which of the following actions can the user perform?
medium
A. Create and drop indexes on collections
B. Insert new documents into collections
C. Read documents from collections
D. Modify documents in collections

Solution

  1. Step 1: Understand dbAdmin role capabilities

    The dbAdmin role allows managing database settings like indexes, stats, and users, but not data changes.
  2. Step 2: Match actions to role permissions

    Creating/dropping indexes is a dbAdmin task. Inserting, reading, or modifying documents require readWrite or read roles.
  3. Final Answer:

    Create and drop indexes on collections -> Option A
  4. Quick Check:

    dbAdmin manages indexes, not data changes [OK]
Hint: dbAdmin manages indexes, not data content [OK]
Common Mistakes:
  • Assuming dbAdmin can insert or modify data
  • Confusing readWrite with dbAdmin
  • Thinking dbAdmin can read data
4. You tried to assign the readWrite role to a user with this command:
db.grantRolesToUser('alice', ['readWrite'])
But it failed. What is the likely cause?
medium
A. The user 'alice' does not exist
B. The role array must contain objects with role and db fields
C. The readWrite role does not exist
D. You must use createUser to assign roles

Solution

  1. Step 1: Check syntax for grantRolesToUser

    The method requires an array of role objects with role and db fields, not just strings.
  2. Step 2: Analyze the given command

    The command uses an array of strings, which is invalid syntax and causes failure.
  3. Final Answer:

    The role array must contain objects with role and db fields -> Option B
  4. Quick Check:

    Roles must be objects with role and db [OK]
Hint: Roles need role+db objects, not strings [OK]
Common Mistakes:
  • Passing roles as strings instead of objects
  • Assuming createUser is needed to add roles to existing users
  • Ignoring user existence errors
5. You want a user to manage database indexes and view data but not modify documents. Which combination of built-in roles should you assign?
hard
A. readWrite only
B. dbAdmin only
C. read and dbAdmin
D. readWrite and dbAdmin

Solution

  1. Step 1: Identify roles for viewing data and managing indexes

    read allows viewing data, dbAdmin allows managing indexes and database settings.
  2. Step 2: Exclude roles that allow modifying documents

    readWrite allows modifying documents, which is not desired here.
  3. Final Answer:

    read and dbAdmin -> Option C
  4. Quick Check:

    View + manage indexes = read + dbAdmin [OK]
Hint: Combine read and dbAdmin to view and manage without edits [OK]
Common Mistakes:
  • Using readWrite which allows document changes
  • Assigning only dbAdmin which lacks read permission
  • Assuming dbAdmin includes readWrite
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