0
0
MongoDBquery~5 mins

Text indexes for search in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Text indexes for search
O(log n + k)
Understanding Time Complexity

When using text indexes in MongoDB, it's important to understand how the search time changes as the amount of data grows.

We want to know how the search speed changes when we look for words in bigger collections.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Create a text index on the 'description' field
db.products.createIndex({ description: "text" })

// Search for documents containing the word 'coffee'
db.products.find({ $text: { $search: "coffee" } })
    

This code creates a text index on a field and then searches for documents containing a specific word.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The database looks up the search word in the text index structure.
  • How many times: The lookup happens once per search query, but the index internally may check multiple entries depending on the word frequency.
How Execution Grows With Input

As the number of documents grows, the index helps keep search fast by avoiding scanning every document.

Input Size (n)Approx. Operations
10Few index lookups, very fast
100More index entries checked, still quick
1000More index entries, but search remains efficient

Pattern observation: The search time grows slowly compared to the number of documents because the index narrows down the search quickly.

Final Time Complexity

Time Complexity: O(log n + k)

This means the search time grows slowly as the collection grows, thanks to the index structure, plus a factor depending on the number of matching documents.

Common Mistake

[X] Wrong: "Searching with a text index scans every document one by one."

[OK] Correct: The text index lets MongoDB jump directly to relevant documents without checking all of them, making search much faster.

Interview Connect

Understanding how text indexes speed up search shows you know how databases handle big data efficiently, a useful skill for many projects.

Self-Check

"What if we searched without a text index? How would the time complexity change?"