Full-Text Search in MongoDB
MongoDB has built-in full-text search capabilities. Instead of sending your search queries to an external service like Elasticsearch, you can search your documents directly in the database.
Text search lets users find documents based on words and phrases in text fields. It's like having a search engine built right into your database.
MongoDB's text search handles stemming, stop words, and relevance scoring automatically. Results are ranked by how well they match your search terms.
Creating Text Indexes
Before you can search, you need to create a text index on the fields you want to search. A text index tells MongoDB to build a search-optimized structure for those fields.
You can create a text index on a single field or multiple fields. When you index multiple fields, MongoDB searches across all of them and combines the results.
Text indexes have some overhead on writes, so only create them on fields that actually need full-text search. For simple prefix matching, a regular index might be better.
db.articles.createIndex({ title: "text", body: "text" })
db.articles.insertMany([
{
title: "Getting Started with MongoDB",
body: "MongoDB is a popular NoSQL database that stores data in flexible documents.",
tags: ["database", "nosql"]
},
{
title: "Advanced Query Techniques",
body: "Learn how to write efficient queries using indexes and aggregation pipelines.",
tags: ["query", "performance"]
}
])
Text Search Queries
To search, use the $text operator in your query. MongoDB will return documents that match your search terms, sorted by relevance.
You can search for single words, phrases, or combinations of terms. MongoDB handles the matching logic for you.
The score field tells you how relevant each result is. Higher scores mean better matches. You can sort by score to get the best results first.
db.articles.find({ $text: { $search: "MongoDB database" } })
db.articles.find(
{ $text: { $search: "MongoDB database" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
db.articles.find(
{ $text: { $search: "\"NoSQL database\"" } },
{ score: { $meta: "textScore" } }
)
Text Search Operators
MongoDB provides several operators for more precise searching. You can include or exclude terms, and even use wildcards.
Use quotes for exact phrases, a minus sign to exclude terms, and wildcards for partial matching. These give you fine control over your search results.
You can also combine text search with regular MongoDB queries. This lets you search for text while filtering by other criteria like dates or categories.
db.articles.find({ $text: { $search: "MongoDB -SQL" } })
db.articles.find({ $text: { $search: "data*" } })
db.articles.find({
$text: { $search: "database performance" },
tags: "performance"
})
db.articles.find(
{ $text: { $search: "query optimization" } },
{ title: 1, body: 1, score: { $meta: "textScore" } }
).limit(5)