Tables vs collections thinking in MongoDB - Performance Comparison
When working with databases, it's important to understand how operations grow as data grows.
Here, we explore how thinking in tables (SQL) compares to collections (MongoDB) affects time complexity.
Analyze the time complexity of querying a collection with embedded documents versus joining tables.
// Find all orders with customer info embedded
db.orders.find({"customer.name": "Alice"})
// Versus joining tables in SQL (conceptual)
// SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id WHERE customers.name = 'Alice';
This snippet shows a MongoDB query searching inside embedded documents compared to a SQL join.
Look at what repeats when the database runs the query.
- Primary operation: Scanning documents in the collection to find matches.
- How many times: Once per document in the collection or table.
As the number of documents or rows grows, the work to find matches grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document checks |
| 100 | 100 document checks |
| 1000 | 1000 document checks |
Pattern observation: The number of checks grows directly with the number of documents or rows.
Time Complexity: O(n)
This means the time to find data grows in a straight line as the data grows.
[X] Wrong: "Using embedded documents always makes queries faster than joins."
[OK] Correct: If there is no index, searching inside embedded documents still requires checking many documents, so it can be just as slow as a join scanning many rows.
Understanding how data structure affects query time helps you explain your design choices clearly and confidently.
"What if we added an index on the embedded field? How would the time complexity change?"