Compound indexes support multi-field filters and sorts. Text indexes power basic full-text search on string fields.
Compound index for filter + sort
db.products.createIndex({ category: 1, price: -1 })
db.products.find({ category: 'tools' }).sort({ price: -1 }).limit(5)Practice: Run on practice in mongosh.
Text index
db.articles.createIndex({ title: 'text', body: 'text' })
db.articles.find({ $text: { $search: 'mongodb index' } }, { score: { $meta: 'textScore' } })
.sort({ score: { $meta: 'textScore' } })
Index limits
One text index per collection (combined fields). For advanced search, consider Atlas Search or external engines.
Important interview questions and answers
- Q: Prefix rule?
A: Compound index {a:1,b:1} helps {a} and {a,b} queries—not always {b} alone. - Q: text index language?
A: Default language stemming affects tokenization.
Self-check
- Why sort price -1 in compound index?
- What operator uses text index?
Tip: Compound index field order must match equality-then-sort query shape.
Interview prep
- Compound prefix?
- Index {a:1,b:1} supports {a} and {a,b} queries.
- $text search?
- Uses text index on string fields.