Running $text Queries With Phrases and Negation
Learners will query with $text using quoted phrases, negated terms, and multi-word expressions, and examine how MongoDB matches documents.
The $text Query Operator
Once a text index exists, you run keyword searches with the $text operator inside a find() filter. The value is an object with a $search string containing the words or phrases you are looking for. MongoDB tokenises your search string the same way it tokenised the indexed fields, then returns documents where at least one indexed field contains a matching token.
// Simple keyword search
db.articles.find({ $text: { $search: 'mongodb index' } });
// This returns documents that contain 'mongodb' OR 'index'
// (or their stemmed variants) in any indexed fieldMulti-Word Searches: OR Semantics
By default, a $text search with multiple words uses OR semantics: a document matches if it contains any of the words. So 'mongodb index' returns documents containing 'mongodb' or 'index' or both. The relevance score (textScore) is higher for documents that contain more of the search terms, but all matching documents are returned regardless.
// OR semantics: matches docs with 'mongodb' OR 'index'
db.articles.find(
{ $text: { $search: 'mongodb index' } },
{ score: { $meta: 'textScore' }, title: 1 }
).sort({ score: { $meta: 'textScore' } });
// Documents with BOTH words score higher and appear firstAll lessons in this course
- Creating a Text Index on String Fields
- Running $text Queries With Phrases and Negation
- Sorting by Text Score With $meta
- Text Index Limitations and When to Use Atlas Search