Text Indexes and Search
Searching for words inside text with $regex is slow on large collections and knows nothing about language. A text index splits string fields into words, removes common stop words ("the", "and"), reduces words to their stem ("beans" → "bean") and lets you search with the $text operator.
Creating a text index
A collection can have one text index, but it can cover several fields:
db.products.createIndex({ name: 'text', tags: 'text' });
print(db.products.find({ $text: { $search: 'chocolate' } }, { name: 1 }).toArray());[ { _id: 17, name: 'Dark Chocolate Bar' } ]
tags is an array, and every element is indexed.
Searching several words
$search is a string of words. A document matches if it contains any of them:
db.products.createIndex({ name: 'text', tags: 'text' });
db.products.find({ $text: { $search: 'green dripper' } }, { name: 1 })
.sort({ _id: 1 })
.forEach(p => print(p._id, p.name));6 Green Sencha
10 Pour-Over Dripper
Special syntax inside the search string:
| Syntax | Meaning | Example |
|---|---|---|
word1 word2 |
either word | 'green dripper' |
"exact phrase" |
the phrase must appear | '"french press"' |
-word |
exclude documents with the word | 'brewing -electric' |
db.products.createIndex({ name: 'text', tags: 'text' });
const names = (search) => db.products.find({ $text: { $search: search } }).sort({ _id: 1 }).toArray().map(p => p.name);
print(names('"french press"'));
print(names('brewing -electric'));[ 'French Press' ]
[ 'Pour-Over Dripper', 'French Press', 'Paper Filters (100)' ]
Stemming
Because words are reduced to their stem, a search for "cookie" finds "Cookies", and "brew" finds documents tagged "brewing":
db.products.createIndex({ name: 'text', tags: 'text' });
const names = (search) => db.products.find({ $text: { $search: search } }).sort({ _id: 1 }).toArray().map(p => p.name);
print(names('cookie'));
print(names('brew'));[ 'Oat Cookies' ]
[
'Pour-Over Dripper',
'French Press',
'Gooseneck Kettle',
'Paper Filters (100)'
]
Searches are also case-insensitive and ignore diacritics by default.
Relevance score
Each match gets a text score: higher when the search words appear more often, or in more heavily weighted fields. Project it with { $meta: 'textScore' } and sort by it to show the best matches first:
db.products.createIndex({ name: 'text', tags: 'text' }, { weights: { name: 3, tags: 1 } });
db.products.find(
{ $text: { $search: 'dark bean' } },
{ name: 1, score: { $meta: 'textScore' } }
).sort({ score: { $meta: 'textScore' }, _id: 1 })
.forEach(p => print(p.score.toFixed(2), p.name));4.10 Espresso Beans
2.00 Dark Chocolate Bar
1.10 Decaf Night Owl
0.75 Ethiopia Yirgacheffe
0.75 Colombia Supremo
With weights, a word in the name counts three times as much as a word in tags, so "Espresso Beans" (dark and bean) ranks first, and "Dark Chocolate Bar" (dark in its name) beats products that are only tagged dark.
$text in aggregations
$text can be used in a $match, but only as the first stage of the pipeline:
db.products.createIndex({ name: 'text', tags: 'text' });
print(db.products.aggregate([
{ $match: { $text: { $search: 'sweet vegan' } } },
{ $group: { _id: '$category', matches: { $sum: 1 } } }
]).toArray());[ { _id: 'snacks', matches: 3 } ]
Limits of text indexes
- One text index per collection, and a query can contain only one
$textexpression. - No fuzzy matching ("expreso" won't find "espresso"), no autocomplete and no partial words.
- For those features, MongoDB Atlas offers Atlas Search (
$searchstage), and many teams use a dedicated search engine.
Test yourself
How many text indexes can a collection have?
- One
- One per field
- Up to 64
- Unlimited
What does { $text: { $search: 'tea -green' } } find?
- Documents with 'tea' and 'green'
- Documents with 'tea' but not 'green'
- Documents with 'tea-green'
- Documents without 'tea'
Why does a search for 'cookie' match 'Oat Cookies'?
- $text uses regex
- Stemming reduces both words to the same stem
- It matches any 6 letters
- Case-insensitivity