0
0
MongoDBquery~5 mins

Text search with text indexes in MongoDB

Choose your learning style9 modes available
Introduction
Text search helps you find documents containing specific words quickly by using special indexes made for text.
You want to find all articles containing a certain word or phrase.
You need to search product descriptions for keywords in an online store.
You want to filter user comments that mention a particular topic.
You want to build a simple search feature for your app's text data.
Syntax
MongoDB
db.collection.createIndex({ fieldName: "text" })
db.collection.find({ $text: { $search: "search words" } })
You create a text index on the fields you want to search.
Use $text with $search to find documents matching the words.
Examples
Create a text index on the 'title' field to search article titles.
MongoDB
db.articles.createIndex({ title: "text" })
Find articles that contain the words 'mongodb' and 'tutorial' in indexed text fields.
MongoDB
db.articles.find({ $text: { $search: "mongodb tutorial" } })
Create a text index on both 'name' and 'description' fields to search product info.
MongoDB
db.products.createIndex({ name: "text", description: "text" })
Search products that mention 'wireless' and 'headphones' in name or description.
MongoDB
db.products.find({ $text: { $search: "wireless headphones" } })
Sample Program
Insert three books, create a text index on the title, then find books with 'MongoDB' in the title.
MongoDB
db.books.insertMany([
  { title: "Learn MongoDB", author: "Alice" },
  { title: "MongoDB Basics", author: "Bob" },
  { title: "Advanced Databases", author: "Carol" }
])
db.books.createIndex({ title: "text" })
db.books.find({ $text: { $search: "MongoDB" } })
OutputSuccess
Important Notes
Text indexes support searching multiple fields at once by listing them in createIndex.
Search is case-insensitive and ignores common words like 'the' or 'and'.
You can use quotes in $search to look for exact phrases.
Summary
Text indexes speed up searching words in text fields.
Use createIndex with 'text' to set up searchable fields.
Use find with $text and $search to find matching documents.