$text

Performs full-text search on string content with support for language-specific stemming, case sensitivity, and phrase matching.

Syntax

{ $text: { $search: <string>, $language: <string>, $caseSensitive: <boolean>, $diacriticSensitive: <boolean> } }

Parameters

$searchstringrequired

The text search string containing words or phrases to search for

$languagestring

Language code for stemming and stop words: "en" (English), "es" (Spanish), "fr" (French), etc.

$caseSensitivestring

Boolean flag for case-sensitive search: "true" or "false" (default)

$diacriticSensitivestring

Boolean flag for diacritic-sensitive search: "true" or "false" (default)

Examples

Basic text search

Search for documents containing specific words in indexed text fields

Query:

db.stores.find({ $text: { $search: "electronics gadgets" } })

Output:

Documents containing "electronics" or "gadgets" in text-indexed fields

Phrase search

Search for exact phrases using quoted strings

Query:

db.stores.find({ $text: { $search: "\"Bed and Bath\"" } })

Output:

Documents containing the exact phrase "Bed and Bath"

Negated search terms

Exclude documents containing specific terms using minus operator

Query:

db.stores.find({ $text: { $search: "furniture -mattress" } })

Output:

Documents containing "furniture" but not "mattress"

Language-specific search

Perform text search with language-specific stemming

Query:

db.stores.find({ $text: { $search: "electronics", $language: "en" } })

Output:

Documents matching "electronics" using English language rules

Case and diacritic sensitive search

Perform exact text matching with case and accent sensitivity

Query:

db.stores.find({ $text: { $search: "Electronics", $caseSensitive: true, $diacriticSensitive: true } })

Output:

Documents containing "Electronics" with exact case and diacritic matching

Scored text search results

Get text search results with relevance scores

Query:

db.stores.find({ $text: { $search: "coffee shop" } }, { score: { $meta: "textScore" } }).sort({ score: { $meta: "textScore" } })

Output:

Documents ranked by text search relevance score in descending order

Related