0
0
MongoDBquery~5 mins

Role-based access control in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Role-based access control
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of roles a user has increases, the time to check if a role exists grows.

Input Size (n)Approx. Operations
10 rolesUp to 10 checks
100 rolesUp to 100 checks
1000 rolesUp to 1000 checks

Pattern observation: The time grows roughly in direct proportion to the number of roles checked.

Final Time Complexity

Time Complexity: O(n)

This means the time to check a role grows linearly with the number of roles the user has.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if roles were stored in a set or indexed structure instead of a list? How would the time complexity change?"