Skip to the workspace
Pebellslearn by building
Creating Indexes  ›  Lesson

Text Indexes

Text 12 minA text index breaks string fields into words, dropping common stop words and reducing words to their stems, so $text queries can match any of several search words and rank results by relevance.

mongodb / Text Indexes

Explore each scene at your own pace.

01 · The rule

The rule

Text Indexes

A customer types "hobbits" into the search box. An equality filter needs the exact string "The Hobbit", and a regular expression can't use a normal index efficiently for words in the middle of a title. A text index is built for this: it splits text into words and searches those.

The rule

Index words, not strings: $text searches stems, ignores stop words, ORs terms.

db.books.createIndex({ title: "text", author: "text" })

db.books.find({ $text: { $search: "hobbits" } })          // The Hobbit
db.books.find({ $text: { $search: "emma circe" } })       // Emma, Circe
db.books.find({ $text: { $search: "herbert" } })          // Dune (by author)

What the index does to each string:

  • Splits it into words and ignores case.
  • Drops stop words, very common words such as "the", "a" and "and" (per language, English by default).
  • Stems words, so "hobbits" and "hobbit" share one entry.

What $search understands:

  • Several words are ORed: "emma circe" matches either.
  • A quoted phrase must appear as written: "\"the hobbit\"".
  • A leading minus excludes: "miller -dune".

Rank the matches with the relevance score:

db.books.find({ $text: { $search: "dune hobbit" } }, { score: { $meta: "textScore" } })
        .sort({ score: { $meta: "textScore" } })

Limits: one text index per collection (list every field you need in it), no typo tolerance and no autocomplete. For those, Atlas offers Atlas Search, a separate full-text engine.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.