← Back to MongoDB Course | Chapter 8: Indexes | Lesson 4 of 7

Text indexes

A text index makes string fields searchable with $text queries.

In this page:

  1. Text indexes
Syntax
javascript
db.collection_name.createIndex({ field1: "text", field2: "text" })

Text indexes

createIndex({ title: "text", body: "text" }) indexes words with stemming and language rules. Weights let some fields count more, and default_language sets the language.

Only one text index is allowed per collection, and queries use $text with $search.

Note: Use weights to rank title matches above body matches.

Example: Text indexes

bash
test> db.articles.createIndex({ title: "text", body: "text" }, { weights: { title: 10, body: 1 }, name: "articles_text" })
articles_text
test> db.articles.find({ $text: { $search: "index performance" } }).limit(2)
[
  { _id: 7, title: 'Index performance tips', body: '...' },
  { _id: 3, title: 'Schema design', body: 'Good indexes improve performance ...' }
]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Creating two text indexes
  2. Expecting substring search
  3. Ignoring language settings
Chapter Summary
  • One text index per collection
  • Multiple fields allowed
  • weights adjust ranking
  • $text and $search query it
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.