0
0
MongoDBquery~5 mins

Custom role creation in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom role creation
O(n)
Understanding Time Complexity

When creating custom roles in MongoDB, it's important to understand how the time to create or update roles changes as the number of privileges grows.

We want to know how the work increases when we add more actions or resources to a role.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

db.createRole({
  role: "customRole",
  privileges: [
    { resource: { db: "test", collection: "users" }, actions: ["find", "update"] },
    { resource: { db: "test", collection: "orders" }, actions: ["insert"] }
  ],
  roles: []
})

This code creates a custom role with a list of privileges, each specifying resources and allowed actions.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Iterating over the privileges array to process each privilege.
  • How many times: Once for each privilege in the list.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n privileges)Approx. Operations
1010 operations (one per privilege)
100100 operations
10001000 operations

Pattern observation: The work grows directly with the number of privileges; doubling privileges doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create a custom role grows linearly with the number of privileges you add.

Common Mistake

[X] Wrong: "Adding more privileges won't affect the creation time much because it's just one command."

[OK] Correct: Each privilege must be processed, so more privileges mean more work and longer creation time.

Interview Connect

Understanding how the number of privileges affects role creation time shows you can think about how database commands scale with input size, a useful skill in real projects.

Self-Check

"What if we added nested roles inside the custom role? How would that change the time complexity?"