Skip to content
LESSON 27 / 50Advancedindexing

Text Indexes & Wildcard ($**) Index Architectures

Text indexes provide tokenization and stemming for keyword search, while Wildcard indexes ($**) index arbitrary, dynamic document schemas and polymorphic attributes.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 27: Text Indexes & Wildcard ($**) Index Architectures

Execution Stage
IXSCAN + FETCH
B-Tree leaf seek
Documents Examined
2
O(log N) lookup
Keys Examined
2
Index keys inspected
Query Latency
0.3 ms
WiredTiger execution time
Explain Plan Output Summary:
{
  "queryPlanner": {
    "winningPlan": {
      "stage": "FETCH",
      "inputStage": {
        "stage": "IXSCAN",
        "indexName": "role_1_country_1",
        "isMultiKey": false,
        "direction": "forward"
      }
    }
  },
  "executionStats": {
    "nReturned": 2,
    "executionTimeMillis": 1,
    "totalKeysExamined": 2,
    "totalDocsExamined": 2
  }
}

1. Formal Definition & Architecture Intent

Text Indexes tokenize string fields, stem root words (e.g. "running" -> "run"), strip stop words, and calculate TF-IDF relevance scores. Wildcard Indexes ({ "$**": 1 } or { "metadata.$**": 1 }) automatically index all scalar fields within dynamic, unpredictable JSON payloads.

2. Explain Like I'm 5 (Mental Model)

A standard index is like looking up an exact word in an alphabetical list. A Text index is like a search engine that understands word roots. A Wildcard index is a magic net that catches every new field without you having to define them one by one.

3. Real-World Architecture Example

Indexing dynamic product attributes where each category has custom keys (color, voltage, size, weight).

Sample BSON Documents:
Collection: db.products
{
  "name": "Drill Pro",
  "attributes": {
    "voltage": "20V",
    "rpm": 1500,
    "wireless": true
  }
}

A wildcard index on "attributes.$**" enables index-accelerated queries on any arbitrary attribute.

4. MQL Implementation Steps

Step 1: Create a full-text search index with language stemming
db.articles.createIndex({ title: "text", body: "text" });
Only one text index is permitted per collection.
Step 2: Query using $text search with relevance sorting
db.articles.find(
  { $text: { $search: "database scaling" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
Sorts results by algorithmic relevance textScore.
Step 3: Create a wildcard index on dynamic subdocuments
db.products.createIndex({ "attributes.$**": 1 });
Indexes all scalar paths within attributes.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
One Text Index LimitA collection can contain at most ONE text index (can cover multiple compound fields).
Wildcard LimitationsWildcard indexes cannot be compound, multikey-compound, or unique.

6. Deep Dive: Wildcard Index Path Expansion Mechanics

When a wildcard index is created on "metadata.$**", WiredTiger flattens every nested object into distinct path-value tuples: metadata.specs.ram = 32, metadata.env = "prod". This is ideal for multi-tenant applications or SaaS platforms where users define custom form fields without pre-defined schemas.

// Wildcard projection filtering (include/exclude paths):
db.products.createIndex(
  { "$**": 1 },
  { wildcardProjection: { "attributes.secret": 0, "history": 0 } }
);
Production Warning: Full text search in MongoDB does not replace dedicated search engines (Elasticsearch/Atlas Search) for fuzzy typo tolerance.

7. Architectural Trade-offs

Advantages
  • •Wildcard indexes eliminate index migration overhead on dynamic polymorphic schemas
  • •Text indexes provide stemming, stop words, and relevance scoring natively
  • •Supports searching across arbitrary nested sub-properties with zero schema setup
Disadvantages & Gotchas
  • •Text indexes are heavy on writes and consume substantial RAM cache
  • •Wildcard indexes consume significant storage if applied to root { "$**": 1 } on deep documents

8. Technical Interview Questions

Q1: When should you choose a Wildcard Index over creating individual compound indexes?

Use Wildcard Indexes when querying dynamic, unpredictable, or user-defined schemas (e.g. an attributes subdocument in an e-commerce catalog or custom metadata in a multi-tenant SaaS application) where the exact field names are unknown in advance or constantly changing.

9. Staff-Level Ready Answer

"Text indexes provide tokenization, language stemming, and relevance scoring (max 1 per collection). Wildcard indexes ({ "$**": 1 }) index dynamic scalar paths across polymorphic schemas, ideal for user-defined attributes without catalog index churn."

10. Quick Knowledge Check

How many Text indexes can be created on a single MongoDB collection?