Attribute pattern for variable fields in MongoDB - Time & Space Complexity
When working with variable fields in MongoDB documents, queries often use attribute patterns to find matching fields.
We want to understand how the time to run these queries changes as the data grows.
Analyze the time complexity of the following MongoDB query using attribute pattern matching.
db.collection.find({
"attributes.color": { $exists: true },
"attributes.size": { $exists: true }
})
.limit(100)
This query finds documents where the "attributes" object has both "color" and "size" fields.
Look for repeated checks or scans in the query process.
- Primary operation: Scanning each document to check if the "attributes" object contains the specified fields.
- How many times: Once per document in the collection until 100 matches are found or all documents are checked.
As the number of documents grows, the query must check more documents to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 document checks |
| 100 | Up to 100 document checks |
| 1000 | Up to 1000 document checks |
Pattern observation: The number of checks grows roughly in direct proportion to the number of documents.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of documents in the collection.
[X] Wrong: "The query will always be fast because it only looks for two fields."
[OK] Correct: Even though the query looks for two fields, MongoDB must check each document's attributes, so the time depends on how many documents there are.
Understanding how queries with variable fields scale helps you explain performance and indexing strategies clearly in real-world situations.
What if we added an index on "attributes.color" and "attributes.size"? How would the time complexity change?