0
0
MongodbHow-ToBeginner · 3 min read

How to Search Text in MongoDB: Syntax and Examples

To search text in MongoDB, first create a text index on the fields you want to search. Then use the $text operator in your query to find documents matching the search string.
📐

Syntax

To search text in MongoDB, you use two main steps:

  • Create a text index on the field(s) you want to search.
  • Use the $text operator in a find query with the $search string.

Example syntax for creating a text index:

db.collection.createIndex({ fieldName: "text" })

Example syntax for searching text:

db.collection.find({ $text: { $search: "search string" } })
mongodb
db.collection.createIndex({ fieldName: "text" })
db.collection.find({ $text: { $search: "search string" } })
💻

Example

This example shows how to create a text index on the description field and then search for documents containing the word "coffee".

mongodb
use mydb

// Create a text index on the description field
db.products.createIndex({ description: "text" })

// Search for documents containing the word 'coffee'
db.products.find({ $text: { $search: "coffee" } })
Output
[ { "_id": ObjectId("..."), "name": "Coffee Maker", "description": "Brews coffee quickly." }, { "_id": ObjectId("..."), "name": "Coffee Beans", "description": "Freshly roasted coffee beans." } ]
⚠️

Common Pitfalls

Common mistakes when searching text in MongoDB include:

  • Not creating a text index before using $text. Without the index, the query will fail.
  • Trying to search multiple fields without a combined text index. You must create a text index on all fields you want to search together.
  • Using $text with fields that are not indexed as text.
  • Expecting case-sensitive or partial matches; MongoDB text search is case-insensitive but does not support partial word matches.

Wrong way (no index):

db.products.find({ $text: { $search: "coffee" } })

Right way (with index):

db.products.createIndex({ description: "text" })
db.products.find({ $text: { $search: "coffee" } })
mongodb
db.products.find({ $text: { $search: "coffee" } })

// Error: text index required

// Correct approach:
db.products.createIndex({ description: "text" })
db.products.find({ $text: { $search: "coffee" } })
📊

Quick Reference

Summary tips for text search in MongoDB:

  • Create a text index on all fields you want to search.
  • Use $text with $search to query text.
  • Text search is case-insensitive and matches whole words.
  • Use quotes in $search for phrase search, e.g., "coffee maker".
  • Use $language option to specify language for stemming and stop words.

Key Takeaways

Always create a text index on fields before using $text search.
Use the $text operator with $search to find matching text in documents.
Text search in MongoDB is case-insensitive and matches whole words, not partial.
Combine multiple fields in one text index to search across them together.
Use quotes in $search for exact phrase matching.