Rows vs documents thinking in MongoDB - Performance Comparison
When working with databases, it helps to understand how data is stored and accessed. Rows and documents are two ways data can be organized.
We want to see how the time to find or process data changes as the amount of data grows.
Analyze the time complexity of the following MongoDB query.
// Find all documents where age is greater than 30
db.users.find({ age: { $gt: 30 } })
This query searches through a collection of user documents to find those with age over 30.
Look for repeated work done by the database engine.
- Primary operation: Scanning each document to check the age field.
- How many times: Once for every document in the collection.
As the number of documents grows, the database checks more documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document checks |
| 100 | 100 document checks |
| 1000 | 1000 document checks |
Pattern observation: The work grows directly with the number of documents.
Time Complexity: O(n)
This means the time to find matching documents grows in a straight line as the collection gets bigger.
[X] Wrong: "Finding documents is always fast because MongoDB stores data as documents."
[OK] Correct: Even with documents, if there is no index, MongoDB must check each document one by one, so time grows with data size.
Understanding how data structure affects search time helps you explain database choices clearly. This skill shows you think about real-world data handling.
"What if we add an index on the age field? How would the time complexity change?"