Role-based access control in MongoDB - Time & Space Complexity
When using role-based access control in MongoDB, we want to know how the time to check permissions changes as the number of roles or users grows.
We ask: How does the system handle more roles or users without slowing down too much?
Analyze the time complexity of the following MongoDB role check.
// Check if user has a role
const user = db.users.findOne({ username: "alice" });
const hasRole = user.roles.includes("readWrite");
if (hasRole) {
// allow action
} else {
// deny action
}
This code finds a user document and checks if the user has a specific role in their roles list.
Look for repeated steps that take time as data grows.
- Primary operation: Searching through the user's roles array to find a matching role.
- How many times: The check goes through each role in the array until it finds a match or finishes.
As the number of roles a user has increases, the time to check if a role exists grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 roles | Up to 10 checks |
| 100 roles | Up to 100 checks |
| 1000 roles | Up to 1000 checks |
Pattern observation: The time grows roughly in direct proportion to the number of roles checked.
Time Complexity: O(n)
This means the time to check a role grows linearly with the number of roles the user has.
[X] Wrong: "Checking a role is always instant no matter how many roles a user has."
[OK] Correct: The system must look through the roles list one by one, so more roles mean more time to check.
Understanding how role checks scale helps you design systems that stay fast as users and roles grow. This skill shows you can think about real-world system performance.
"What if roles were stored in a set or indexed structure instead of a list? How would the time complexity change?"