0
0
MongoDBquery~5 mins

Text indexes for search in MongoDB

Choose your learning style9 modes available
Introduction
Text indexes help you quickly find documents containing specific words or phrases in your database.
You want to search for products by name or description in an online store.
You need to find articles containing certain keywords in a blog database.
You want users to search messages or comments by text content.
You want to filter documents by matching words in multiple fields.
Syntax
MongoDB
db.collection.createIndex({ fieldName: "text" })
You create a text index on one or more fields to enable text search.
Only one text index is allowed per collection, but it can cover multiple fields.
Examples
Create a text index on the 'title' field to search book titles.
MongoDB
db.books.createIndex({ title: "text" })
Create a text index on both 'title' and 'content' fields to search in both.
MongoDB
db.articles.createIndex({ title: "text", content: "text" })
Create a text index on 'description' to search product descriptions.
MongoDB
db.products.createIndex({ description: "text" })
Sample Program
This example inserts three movie documents, creates a text index on 'title' and 'description', then searches for movies containing the word 'space'.
MongoDB
db.movies.insertMany([
  { title: "Star Wars", description: "A space adventure" },
  { title: "Star Trek", description: "Exploring the galaxy" },
  { title: "The Martian", description: "Survival on Mars" }
])
db.movies.createIndex({ title: "text", description: "text" })
db.movies.find({ $text: { $search: "space" } })
OutputSuccess
Important Notes
Text search is case-insensitive and ignores common words like 'the' or 'and'.
You can use $text with $search to find documents matching words or phrases.
Text indexes support language-specific rules for better search results.
Summary
Text indexes let you search text inside fields quickly.
Create text indexes on one or more fields but only one per collection.
Use $text and $search to find documents matching your search words.