Bird
Raised Fist0
MongoDBquery~10 mins

Custom role creation in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom role creation
Start
↓
Define Role Name
↓
Specify Privileges
↓
Specify Resources
↓
Create Role Command
↓
Role Created in Database
↓
Assign Role to User
↓
End
The flow shows defining a role name, specifying privileges and resources, creating the role, and then assigning it to a user.
Execution Sample
MongoDB
db.createRole({
  role: "readWriteReports",
  privileges: [
    { resource: { db: "reportsDB", collection: "sales" }, actions: ["find", "insert"] }
  ],
  roles: []
})
This code creates a custom role named 'readWriteReports' with find and insert privileges on the sales collection in reportsDB.
Execution Table
StepActionInput/CommandResult/Output
1Define role namerole: "readWriteReports"Role name set to 'readWriteReports'
2Specify privileges{ resource: { db: "reportsDB", collection: "sales" }, actions: ["find", "insert"] }Privileges set for find and insert on sales collection
3Specify inherited rolesroles: []No inherited roles specified
4Run createRole commanddb.createRole({...})Role 'readWriteReports' created successfully
5Assign role to userdb.grantRolesToUser("alice", [{ role: "readWriteReports", db: "admin" }])Role assigned to user 'alice'
6Verify role assignmentdb.getUser("alice")User 'alice' has role 'readWriteReports'
7End-Custom role creation and assignment complete
💡 Process ends after role creation and assignment to user.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4After Step 5Final
roleNameundefinedreadWriteReportsreadWriteReportsreadWriteReportsreadWriteReportsreadWriteReports
privilegesundefinedundefined[{db: 'reportsDB', collection: 'sales', actions: ['find','insert']}][{db: 'reportsDB', collection: 'sales', actions: ['find','insert']}][{db: 'reportsDB', collection: 'sales', actions: ['find','insert']}][{db: 'reportsDB', collection: 'sales', actions: ['find','insert']}]
rolesundefinedundefined[][][][]
userRolesundefinedundefinedundefinedundefined[{role: 'readWriteReports', db: 'admin'}][{role: 'readWriteReports', db: 'admin'}]
Key Moments - 3 Insights
Why do we specify an empty array for 'roles' when creating a custom role?
The 'roles' array lists roles this new role inherits from. An empty array means it does not inherit any roles. See execution_table step 3 where 'roles: []' means no inherited roles.
What happens if we forget to assign the new role to a user?
The role exists but no user has its privileges. The user won't gain any new permissions. See execution_table step 5 where role assignment to user 'alice' happens.
Can we assign privileges on multiple collections in one role?
Yes, by adding multiple privilege objects in the 'privileges' array. Here, only one collection is shown for simplicity (step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the role name after step 1?
A"alice"
B"reportsDB"
C"readWriteReports"
Dundefined
💡 Hint
Check the 'Action' and 'Result/Output' columns in row for step 1.
At which step is the role assigned to the user?
AStep 3
BStep 5
CStep 2
DStep 7
💡 Hint
Look for 'Assign role to user' in the 'Action' column.
If we add another collection privilege, which variable in variable_tracker changes?
Aprivileges
BroleName
Croles
DuserRoles
💡 Hint
Check which variable holds the list of privileges in variable_tracker.
Concept Snapshot
Custom Role Creation in MongoDB:
- Use db.createRole() with role name, privileges, and roles.
- Privileges specify actions on resources (db, collection).
- Roles array is for inherited roles (can be empty).
- Assign created role to users with db.grantRolesToUser().
- Verify with db.getUser().
Full Transcript
This visual execution traces creating a custom role in MongoDB. First, we define the role name 'readWriteReports'. Next, we specify privileges allowing 'find' and 'insert' on the 'sales' collection in 'reportsDB'. We set roles to an empty array meaning no inherited roles. Then we run the createRole command which creates the role in the database. After that, we assign this role to user 'alice' using grantRolesToUser. Finally, we verify the assignment by fetching the user details. Variables like roleName, privileges, roles, and userRoles change step by step as shown. Key moments clarify why roles array can be empty, the importance of assigning roles to users, and how to add multiple privileges. The quiz tests understanding of role name, assignment step, and privilege variable. The snapshot summarizes the commands and flow for quick reference.

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