0% completed
Text indexes in MongoDB are used to support text search queries on string content. They enable efficient searching for words or phrases within text fields and support language-specific text search, which considers language rules for tokenization, stemming, and stop words.
Text indexes are particularly useful for applications that require full-text search capabilities, such as search engines, content management systems, and applications with rich text content.
Key Points:
db.collection.createIndex({ <field>: "text" }, { <option1>: <value1>, <option2>: <value2>, ... })
Let's insert some documents into the articles
collection:
db.articles.insertMany([ { title: "Introduction to MongoDB", content: "MongoDB is a NoSQL database that offers high performance and scalability.", tags: ["MongoDB", "NoSQL", "Database"] }, { title: "Advanced MongoDB Features", content: "Learn about advanced features in MongoDB such as sharding and replication.", tags: ["MongoDB", "Advanced"] }, { title: "Text Search in MongoDB", content: "Text search in MongoDB allows you to perform efficient text searches on string content.", tags: ["MongoDB", "Text Search"] }, { title: "Indexing in MongoDB", content: "Indexing improves query performance by creating indexes on collections.", tags: ["MongoDB", "Indexing"] }, { title: "Aggregation in MongoDB", content: "Aggregation operations process data records and return computed results.", tags: ["MongoDB", "Aggregation"] } ])
Create a text index on the title
and content
fields:
db.articles.createIndex({ title: "text", content: "text" }, { default_language: "english" })
db.articles.createIndex({ title: "text", content: "text" }, { default_language: "english" })
: This command creates a text index on the title
and content
fields. The default_language
option specifies that the text search will use English language rules for tokenization and stemming.Example 1: Simple Text Search
db.articles.find({ $text: { $search: "MongoDB" } })
title
or content
fields.Example 2: Text Search with Sorting by Relevance
db.articles.find({ $text: { $search: "MongoDB features" } }, { score: { $meta: "textScore" } }).sort({ score: { $meta: "textScore" } })
textScore
.Text indexes in MongoDB are essential for enabling full-text search capabilities. By indexing text fields, MongoDB can efficiently search for words or phrases within text content, supporting language-specific rules and relevance-based ranking.
.....
.....
.....