Working with Text Search
1. Creating Text Index
| Form | Effect |
|---|---|
createIndex({title:"text", body:"text"}) | Multi-field text index |
| Limit | One text index per collection |
2. Performing Text Search
| Operator | Form |
|---|---|
| $text | find({$text: {$search: "terms"}}) |
| Default | Match 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
| Pattern | Effect |
|---|---|
| "exact phrase" | Quoted = exact phrase match |
| term1 "phrase" | Mix terms + phrases |
4. Excluding Terms
| Pattern | Effect |
|---|---|
| term -unwanted | Prefix - to exclude |
| Whole word | Exclusion is per word, not substring |
5. Setting Text Search Language
| Form | Effect |
|---|---|
{$search: "x", $language: "spanish"} | Per-query language |
| "none" | Disable stemming/stop-words |
6. Sorting by Text Score ($meta: "textScore")
| Aspect | Detail |
|---|---|
| Score range | Unbounded positive (term freq + field weight) |
| Required projection | Include score field for sort |
7. Using Case-Sensitive Search
| Option | Effect |
|---|---|
| $caseSensitive: true | Match case exactly (default false) |
| Performance | Slightly slower |
8. Using Diacritic-Sensitive Search
| Option | Effect |
|---|---|
| $diacriticSensitive: true | café ≠ cafe (default false) |
| Default | Accent-insensitive in text v3 (4.0+) |
9. Combining Text Search with Other Queries
| Pattern | Effect |
|---|---|
{$text:{$search:"x"}, status:"published"} | Text + scalar filter |
| Compound text index | Add equality prefix for selectivity: {tenantId:1, title:"text"} |
10. Understanding Text Index Limitations
| Limitation | Detail |
|---|---|
| One per collection | Cannot have multiple text indexes |
| No partial matching | Whole-word stem only |
| No fuzzy / typo tolerance | Use Atlas Search |
| Sort limit | Cannot sort by other fields alongside text score easily |
11. Using Text Search with Aggregation
| Aspect | Detail |
|---|---|
| Form | $match with $text must be FIRST stage |
| Score field | Use {$meta: "textScore"} in $project or $addFields |