Atlas search overview in MongoDB - Time & Space Complexity
When using Atlas Search in MongoDB, it's important to understand how the time to find results changes as your data grows.
We want to know how the search time changes when there are more documents to look through.
Analyze the time complexity of the following Atlas Search query.
db.collection.aggregate([
{
$search: {
index: 'default',
text: {
query: 'coffee',
path: 'description'
}
}
}
])
This query searches the 'description' field of documents for the word 'coffee' using an Atlas Search index.
Look for repeated work done during the search.
- Primary operation: Searching the inverted index for matching terms.
- How many times: Once per query, but the index lookup touches entries related to the query term.
As the number of documents grows, the index grows too, but searching the index stays efficient.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Few index lookups |
| 100 | More index lookups, still fast |
| 1000 | More index lookups, but still efficient |
Pattern observation: The search time grows slowly compared to the number of documents because the index helps find matches quickly.
Time Complexity: O(log n + k)
This means the search time grows slowly as the data grows, thanks to the index structure, plus a term proportional to the number of results returned.
[X] Wrong: "Searching with Atlas Search takes as long as scanning every document."
[OK] Correct: Atlas Search uses indexes that let it jump directly to matching documents, so it doesn't check every document one by one.
Understanding how indexes speed up search is a valuable skill. It shows you know how databases handle large data efficiently.
"What if we removed the Atlas Search index and searched without it? How would the time complexity change?"