Built-in roles (read, readWrite, dbAdmin) in MongoDB - Time & Space Complexity
When using built-in roles in MongoDB, it's important to understand how the time to check permissions grows as the number of operations increases.
We want to know how the system handles permission checks as more database actions happen.
Analyze the time complexity of permission checks using built-in roles.
// Example: Checking user permissions for a read operation
const user = db.getUser("alice");
if (user.roles.some(role => role.role === "read")) {
db.collection.find({});
}
// Roles: read, readWrite, dbAdmin
// Each role grants different access levels
This code checks if a user has the 'read' role before allowing a read operation on a collection.
Look at what repeats when checking permissions.
- Primary operation: Checking if the user's roles include the required role.
- How many times: Once per operation that requires permission.
The number of roles a user has is usually small and fixed, so checking roles stays quick even if many operations happen.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 operations | 10 role checks |
| 100 operations | 100 role checks |
| 1000 operations | 1000 role checks |
Pattern observation: The time grows linearly with the number of operations, but each role check is very fast because roles list is short.
Time Complexity: O(n)
This means the total time to check permissions grows directly with the number of operations performed.
[X] Wrong: "Checking roles takes a long time because the database is big."
[OK] Correct: Role checks depend on the user's roles, which are few, not on the database size.
Understanding how permission checks scale helps you explain security and performance in real applications confidently.
"What if a user had hundreds of roles assigned? How would that affect the time complexity of permission checks?"