Creating users and roles in MongoDB - Performance & Efficiency
When we create users and roles in MongoDB, we want to know how the time it takes changes as we add more users or roles.
We ask: How does the work grow when the number of users or roles grows?
Analyze the time complexity of the following code snippet.
db.createUser({
user: "alice",
pwd: "password123",
roles: [ { role: "readWrite", db: "sales" } ]
});
db.createRole({
role: "reporter",
privileges: [ { resource: { db: "sales", collection: "reports" }, actions: [ "find" ] } ],
roles: []
});
This code creates one user and one role with specific permissions in the database.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Indexed lookup to check existing users and roles to ensure no duplicates before creation.
- How many times: This check happens once per user or role creation.
MongoDB uses indexes to perform a fast lookup for duplicates, regardless of the number of existing users or roles.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 indexed lookup |
| 100 | 1 indexed lookup |
| 1000 | 1 indexed lookup |
Pattern observation: The work remains constant as the number of users or roles already in the system grows.
Time Complexity: O(log n)
This means the time to create a user or role grows logarithmically with the number of existing users or roles, which is effectively very fast and close to constant time for practical purposes.
[X] Wrong: "Creating a user or role takes longer as more exist because it scans all entries."
[OK] Correct: MongoDB uses indexes on usernames and rolenames for fast O(log n) lookups, which is effectively constant time.
Understanding how user and role creation scales (logarithmic time due to indexing) helps you explain system behavior clearly and shows you think about real database operations.
"What if we batch create 100 users at once? How would the time complexity change?"