Custom role creation in MongoDB - Time & Space 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.
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 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.
Explain the growth pattern intuitively.
| Input Size (n privileges) | Approx. Operations |
|---|---|
| 10 | 10 operations (one per privilege) |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly with the number of privileges; doubling privileges doubles the work.
Time Complexity: O(n)
This means the time to create a custom role grows linearly with the number of privileges you add.
[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.
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.
"What if we added nested roles inside the custom role? How would that change the time complexity?"