Script Valley
MongoDB: Complete Course
Indexing and Query PerformanceLesson 3.3

MongoDB text indexes and full-text search explained

text index creation, $text operator, $search, score metadata, text index limitations, language support, Atlas Search vs text index

Creating a text index

MongoDB text index tokenization

A text index tokenizes and stems string fields so documents can be found by keyword. MongoDB automatically handles stop words and morphological stemming for the configured language. You can have only one text index per collection, but it can span multiple fields simultaneously by listing each field with the value 'text'.

// Create a compound text index covering title and body
await db.collection('articles').createIndex({
  title: 'text',
  body: 'text'
})

// Basic full-text search — matches documents containing any of the words
const results = await db.collection('articles').find({
  $text: { $search: 'mongodb indexing performance' }
}).toArray()

// Include relevance score and sort by it
const scored = await db.collection('articles').find(
  { $text: { $search: 'aggregation pipeline' } },
  { score: { $meta: 'textScore' } }
).sort({ score: { $meta: 'textScore' } }).toArray()

// Phrase search — wrap the phrase in escaped double quotes
db.collection('articles').find({
  $text: { $search: '"aggregation pipeline"' }
})

// Exclude a word with a minus prefix
db.collection('articles').find({
  $text: { $search: 'mongodb -compass' }
})

Limitations you must know

Text indexes do not support partial or fuzzy matching — searching for mongo does not match documents containing mongodb. Only one text index is allowed per collection. For production-grade search with autocomplete, typo-tolerance, and faceted filtering, use MongoDB Atlas Search which runs on Apache Lucene and drops in as an aggregation stage.

Up next

How to use explain() to diagnose slow MongoDB queries

Sign in to track progress