0PricingLogin
MongoDB Academy · Lesson

Creating a Text Index on String Fields

Learners will create single-field and wildcard text indexes and understand the tokenisation and stemming MongoDB applies.

What Is a Text Index?

A text index is a special MongoDB index type that tokenises and stems the words in string fields so you can run full-text keyword searches. Unlike a regular index that stores exact field values, a text index breaks each string into individual words, removes stop words (like 'the', 'is'), and stores the resulting tokens in a B-tree. This makes it possible to search for 'mongodb tutorial' and match documents containing 'mongodb tutorials'.

Creating a Single-Field Text Index

Pass the string 'text' as the index direction to tell MongoDB to create a text index on that field. You can only have one text index per collection, but it can span multiple fields. The index builds in the background and maintains the token store automatically as documents are inserted or updated.

// Text index on the 'description' field
db.products.createIndex({ description: 'text' });

// Now you can run full-text searches
db.products.find({ $text: { $search: 'wireless headphones' } });

All lessons in this course

  1. Creating a Text Index on String Fields
  2. Running $text Queries With Phrases and Negation
  3. Sorting by Text Score With $meta
  4. Text Index Limitations and When to Use Atlas Search
← Back to MongoDB Academy