← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 7 of 7

Text search basics

A text index enables $text queries that search words in string fields with stemming and scoring.

In this page:

  1. Text search basics
Syntax
javascript
db.collection_name.createIndex({ field: "text" })
db.collection_name.find({ $text: { $search: "words" } })

Text search basics

Create one text index per collection over one or more string fields, then query with { $text: { $search: "words" } }. Results can be sorted by relevance with the textScore meta projection.

Text search handles word stemming and stop words but not partial words; Atlas Search offers richer options.

Note: A collection can have only one text index.

Example: Text search basics

bash
test> db.articles.createIndex({ title: "text", body: "text" })
title_text_body_text
test> db.articles.insertMany([
...   { _id: 1, title: "Learning MongoDB", body: "Documents and collections" },
...   { _id: 2, title: "Cooking pasta", body: "Boil water" }
... ])
test> db.articles.find({ $text: { $search: "mongodb documents" } }, { title: 1, score: { $meta: "textScore" } })
[ { _id: 1, title: 'Learning MongoDB', score: 1.3333333333333333 } ]

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

Related Topics
Common Mistakes
  1. Querying $text without a text index
  2. Expecting partial word matches
  3. Creating several text indexes on one collection
Chapter Summary
  • Create a text index first
  • Query with $text and $search
  • Sort by textScore for relevance
  • Only one text index per collection
🔒

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.