Dot notation for embedded documents in MongoDB - Time & Space Complexity
When we use dot notation to access embedded documents in MongoDB, we want to know how the time to find data changes as the data grows.
We ask: How does the search time grow when we look inside nested fields?
Analyze the time complexity of the following code snippet.
// Find all users where the city in the address is 'New York'
db.users.find({ 'address.city': 'New York' })
This code searches for users whose embedded address document has a city field equal to 'New York'.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each document in the collection to check the embedded field.
- How many times: Once per document in the collection (n times).
As the number of documents grows, the time to check each embedded field grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks of embedded city field |
| 100 | 100 checks of embedded city field |
| 1000 | 1000 checks of embedded city field |
Pattern observation: The number of checks grows directly with the number of documents.
Time Complexity: O(n)
This means the time to find matching documents grows in direct proportion to the number of documents.
[X] Wrong: "Using dot notation makes the search instant no matter how many documents there are."
[OK] Correct: Dot notation just tells MongoDB where to look inside documents, but it still checks each document unless there is an index.
Understanding how accessing embedded fields affects search time helps you explain database queries clearly and shows you know how data structure impacts performance.
"What if we add an index on 'address.city'? How would the time complexity change?"