KeplerGrid guide

Search MongoDB documents with a text index and $text

Search for words and quoted phrases on a self-managed MongoDB collection. Test the same index against both title and body.

Load the practice collection

Run once in mongosh against a development instance with an empty articles practice collection.

const lab = db.getSiblingDB("keplergrid_practice")
lab.articles.insertMany([
  { _id: "guide", title: "Field guide", body: "A guide to forest birds" },
  { _id: "trail", title: "Forest trail", body: "Birds by the river" },
  { _id: "garden", title: "Garden notes", body: "Growing basil" }
])
lab.articles.createIndex({ title: "text", body: "text" }, { name: "article_text" })

In KeplerGrid, open keplergrid_practice.articles with a Read only connection.

Search both indexed fields in Documents

Paste this filter into KeplerGrid Documents to look for forest or river. Unquoted search terms are combined with OR.

{ "$text": { "$search": "forest river" } }

The search returns guide and trail. Word analysis depends on the text index language. Use an ordinary equality or prefix filter when you need different matching behavior, such as an exact code or an anchored prefix.

Search for a phrase in the given order

Put quotes inside the search string. In Extended JSON, escape the inner quotes with a backslash.

{ "$text": { "$search": "\"forest birds\"" } }

Only guide matches the phrase. trail has both words across its fields but lacks the phrase. A collection can have one text index that covers several fields. The examples use MongoDB’s built-in text index.

See how to index array values for exact membership queries or revisit the related KeplerGrid walkthrough.

Next, Extract parts of a MongoDB string with $regexFind.