Database and collection creation in MongoDB - Time & Space Complexity
When we create a database or a collection in MongoDB, it's important to know how the time it takes grows as we add more data or collections.
We want to understand how the work changes when we create new databases or collections.
Analyze the time complexity of the following code snippet.
// Create a new database and collection
use myNewDatabase;
db.createCollection('myNewCollection');
// Insert a document into the collection
db.myNewCollection.insertOne({ name: 'Alice', age: 30 });
This code creates a new database and a collection, then inserts one document into it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating the database and collection is a single setup operation without loops.
- How many times: Each command runs once; no repeated loops or traversals here.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 database, 1 collection | Few operations to create and setup |
| 10 databases, 10 collections | About 10 times more operations, each creation is separate |
| 100 databases, 100 collections | About 100 times more operations, linear growth |
Pattern observation: Creating databases and collections grows linearly with how many you create, but each creation itself is a simple, quick operation.
Time Complexity: O(n)
This means the time to create multiple databases or collections grows directly in proportion to how many you create.
[X] Wrong: "Creating a database or collection takes the same time no matter how many exist already."
[OK] Correct: Each creation is a separate operation, so more creations mean more total time, even if each one is quick.
Understanding how simple setup operations scale helps you explain system behavior clearly and shows you know what happens behind the scenes.
"What if we created collections inside an existing database instead of new databases each time? How would the time complexity change?"