String and number types in MongoDB - Time & Space Complexity
When working with string and number types in MongoDB, it is important to understand how operations on these data types grow as the data size increases.
We want to know how the time to process these types changes when we handle more data.
Analyze the time complexity of the following MongoDB query.
db.collection.find({
$or: [
{ name: { $type: "string" } },
{ age: { $type: "int" } }
]
})
This query finds documents where the field name is a string or the field age is a number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each document to check the type of fields
nameandage. - How many times: Once per document in the collection.
As the number of documents grows, the query checks each document's fields one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows directly with the number of documents.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of documents increases.
[X] Wrong: "Checking types is instant and does not depend on data size."
[OK] Correct: Each document must be checked individually, so more documents mean more work.
Understanding how queries scale with data size helps you write efficient database operations and explain your reasoning clearly in interviews.
"What if we added an index on the name field? How would the time complexity change?"