Working with Text Search

1. Creating Text Index

FormEffect
createIndex({title:"text", body:"text"})Multi-field text index
LimitOne text index per collection
OperatorForm
$textfind({$text: {$search: "terms"}})
DefaultMatch any term (OR)
Score{score: {$meta: "textScore"}} in projection
db.articles.find(
  { $text: { $search: "mongodb performance" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });

3. Using Search Phrases

PatternEffect
"exact phrase"Quoted = exact phrase match
term1 "phrase"Mix terms + phrases

4. Excluding Terms

PatternEffect
term -unwantedPrefix - to exclude
Whole wordExclusion is per word, not substring

5. Setting Text Search Language

FormEffect
{$search: "x", $language: "spanish"}Per-query language
"none"Disable stemming/stop-words

6. Sorting by Text Score ($meta: "textScore")

AspectDetail
Score rangeUnbounded positive (term freq + field weight)
Required projectionInclude score field for sort
OptionEffect
$caseSensitive: trueMatch case exactly (default false)
PerformanceSlightly slower
OptionEffect
$diacriticSensitive: truecafé ≠ cafe (default false)
DefaultAccent-insensitive in text v3 (4.0+)

9. Combining Text Search with Other Queries

PatternEffect
{$text:{$search:"x"}, status:"published"}Text + scalar filter
Compound text indexAdd equality prefix for selectivity: {tenantId:1, title:"text"}

10. Understanding Text Index Limitations

LimitationDetail
One per collectionCannot have multiple text indexes
No partial matchingWhole-word stem only
No fuzzy / typo toleranceUse Atlas Search
Sort limitCannot sort by other fields alongside text score easily

11. Using Text Search with Aggregation

AspectDetail
Form$match with $text must be FIRST stage
Score fieldUse {$meta: "textScore"} in $project or $addFields