Text Search
Full-text indexes, $text operator, and Atlas Search
Skills taught: mongodb.text-search
Full-Text Search in MongoDB
MongoDB's text indexes enable full-text search across string fields. Unlike regular indexes that match exact values, text indexes tokenize text into words, apply stemming (run → running/ran), and remove stop words. The $text operator searches across all text-indexed fields simultaneously.
Creating a Text Index
// Create a text index on one field
await articles.createIndex({ title: 'text' });
// Create a text index on multiple fields
await articles.createIndex({
title: 'text',
body: 'text',
tags: 'text'
});
// Now $text searches across all three fields simultaneously
// Weighted text index — title matches count more than body
await articles.createIndex(
{ title: 'text', body: 'text' },
{ weights: { title: 10, body: 1 }, name: 'article_text_index' }
);
// A word match in title scores 10x higher than in body
// Language-specific index (uses correct stemming and stop words)
await articles.createIndex(
{ title: 'text', body: 'text' },
{ default_language: 'english' } // default is English
);
// Note: a collection can have ONLY ONE text index
Searching with $text
// Basic search — finds documents containing 'mongodb' OR 'database'
const results = await articles.find(
{ $text: { $search: 'mongodb database' } }
).toArray();
// Phrase search — exact phrase in double quotes
const phraseResults = await articles.find(
{ $text: { $search: '"aggregation pipeline"' } } // exact phrase
).toArray();
// Negation — find documents with 'mongodb' but NOT 'sql'
const noSQL = await articles.find(
{ $text: { $search: 'mongodb -sql' } } // minus prefix excludes a term
).toArray();
// Get relevance score and sort by it
const ranked = await articles.find(
{ $text: { $search: 'mongodb aggregation pipeline' } },
{ projection: { score: { $meta: 'textScore' }, title: 1, _id: 0 } }
).sort({ score: { $meta: 'textScore' } }) // sort by relevance
.toArray();
console.log('Top results:');
ranked.forEach(r => console.log(r.title, '— score:', r.score.toFixed(2)));
// Combine $text with other filters
const recentResults = await articles.find({
$text: { $search: 'nodejs express' }, // text search
status: 'published', // regular filter
publishedAt: { $gte: new Date('2025-01-01') } // date filter
}, {
projection: { title: 1, score: { $meta: 'textScore' }, publishedAt: 1 }
}).sort({ score: { $meta: 'textScore' } })
.limit(10)
.toArray();
Atlas Search — Advanced Full-Text Search
MongoDB Atlas Search (powered by Apache Lucene) goes far beyond the native $text operator. It supports fuzzy matching (typo tolerance), autocomplete, faceted search, and custom analyzers — without running a separate Elasticsearch service.
// Atlas Search — uses $search aggregation stage (not $text)
// Requires: MongoDB Atlas cluster with an Atlas Search index defined
// Basic Atlas Search
const results = await articles.aggregate([
{
$search: {
index: 'default', // name of your Atlas Search index
text: {
query: 'mongodb aggregation',
path: ['title', 'body'], // fields to search
fuzzy: { maxEdits: 1 } // tolerate 1 typo!
}
}
},
{
$project: {
title: 1,
score: { $meta: 'searchScore' }
}
},
{ $sort: { score: -1 } },
{ $limit: 10 }
]).toArray();
// Autocomplete (as you type) — requires autocomplete field mapping in Atlas Search index
const suggestions = await articles.aggregate([
{
$search: {
autocomplete: {
query: 'mong', // partial input
path: 'title',
fuzzy: { maxEdits: 1 } // tolerate typos in autocomplete too
}
}
},
{ $limit: 5 },
{ $project: { title: 1, _id: 0 } }
]).toArray();
console.log('Suggestions:', suggestions.map(s => s.title));
MongoDB $text vs Atlas Search
- MongoDB $text: Built-in full-text search using native text indexes
- Atlas Search: Lucene-powered full-text search built into MongoDB Atlas
Tip: For production search with autocomplete or typo tolerance, skip native $text and use Atlas Search directly. It provides Elasticsearch-quality search without running a separate service, as long as you're on MongoDB Atlas.
Frequently Asked Questions
Can I have multiple text indexes per collection?
No. A collection can have only one text index, but it can cover multiple fields. createIndex({ title: 'text', body: 'text', tags: 'text' }) creates a single text index across all three fields.
Does $text search support partial word matching (like LIKE '%term%' in SQL)?
No. MongoDB $text search only matches whole words (after stemming). 'ongo' won't match 'mongodb'. For prefix matching and autocomplete, use Atlas Search with the autocomplete field mapping, or use a regex query: { field: /ongo/i } (but regex queries are slow without an index).
What is a textScore and how do I use it?
textScore is a relevance score computed by MongoDB based on how many times the search terms appear in the document and their frequency across all documents (TF-IDF). Access it in projection with { score: { $meta: 'textScore' } } and sort by it with .sort({ score: { $meta: 'textScore' } }) to get the most relevant results first.