5 min read
•Question 17 of 27mediumHow do you implement text search in MongoDB?
Full-text search capabilities.
What You'll Learn
- Creating text indexes
- Text search queries
- Search score and relevance
Create Text Index
code.jsJavaScript
// Single field
db.articles.createIndex({ content: "text" });
// Multiple fields
db.articles.createIndex({ title: "text", content: "text" });
// With weights
db.articles.createIndex(
{ title: "text", content: "text" },
{ weights: { title: 10, content: 1 } }
);Basic Text Search
code.jsJavaScript
// Search for words
db.articles.find({ $text: { $search: "mongodb tutorial" } });
// Phrase search (exact match)
db.articles.find({ $text: { $search: '"mongodb tutorial"' } });
// Exclude words
db.articles.find({ $text: { $search: "mongodb -mysql" } });Search Score
code.jsJavaScript
// Get relevance score
db.articles.find(
{ $text: { $search: "mongodb" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });Mongoose Implementation
code.jsJavaScript
const articleSchema = new mongoose.Schema({
title: String,
content: String
});
articleSchema.index({ title: 'text', content: 'text' });
// Search
const results = await Article.find(
{ $text: { $search: query } },
{ score: { $meta: 'textScore' } }
)
.sort({ score: { $meta: 'textScore' } })
.limit(10);Limitations
- One text index per collection
- Case-insensitive by default
- No partial word matching
- Consider Elasticsearch for advanced needs