TExcelTAD
Home › MongoDB › Text Indexes and Search

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:

mongosh · try it yourself
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:

mongosh · try it yourself
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'
mongosh · try it yourself
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":

mongosh · try it yourself
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:

mongosh · try it yourself
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:

mongosh · try it yourself
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 $text expression.
  • No fuzzy matching ("expreso" won't find "espresso"), no autocomplete and no partial words.
  • For those features, MongoDB Atlas offers Atlas Search ($search stage), and many teams use a dedicated search engine.

Test yourself

How many text indexes can a collection have?

  1. One
  2. One per field
  3. Up to 64
  4. Unlimited

What does { $text: { $search: 'tea -green' } } find?

  1. Documents with 'tea' and 'green'
  2. Documents with 'tea' but not 'green'
  3. Documents with 'tea-green'
  4. Documents without 'tea'

Why does a search for 'cookie' match 'Oat Cookies'?

  1. $text uses regex
  2. Stemming reduces both words to the same stem
  3. It matches any 6 letters
  4. Case-insensitivity