Introduction
A Text Index in MongoDB is used to efficiently search text stored in string fields. It is useful when you want to find documents containing specific words instead of matching an entire field value. In this chapter, you will practice creating text indexes, using the $text operator, searching for words and phrases, checking text indexes, and removing them. MongoDB Text Index Practice Questions with Solutions to help you understand the concepts.
Q1. Create a Text Index on a Description Field
Problem Statement
Create a text index on the description field of the products collection.
MongoDB Command / Query
db.products.createIndex({
description: "text"
})
Expected Output
description_text
Explanation
The "text" index type tells MongoDB that the field will be used for text searching.
Q2. Insert Products for Text Searching
Problem Statement
Insert some products containing different descriptions.
MongoDB Command / Query
db.products.insertMany([
{
name: "Laptop",
description: "Powerful laptop for programming and data analysis"
},
{
name: "Keyboard",
description: "Mechanical keyboard for programmers"
},
{
name: "Monitor",
description: "Large monitor for coding and office work"
},
{
name: "Mouse",
description: "Wireless mouse for everyday computer use"
}
])
Expected Output
{
acknowledged: true,
insertedIds: {
"0": ObjectId("..."),
"1": ObjectId("..."),
"2": ObjectId("..."),
"3": ObjectId("...")
}
}
Explanation
These documents provide sample text that can be searched using the text index.
Q3. Search for a Single Word
Problem Statement
Find all products whose indexed text contains the word programming.
MongoDB Command / Query
db.products.find({
$text: {
$search: "programming"
}
})
Expected Output
{
name: "Laptop",
description: "Powerful laptop for programming and data analysis"
}
Explanation
The $text operator searches the fields covered by the text index.
Q4. Search for Another Word
Problem Statement
Find products containing the word coding.
MongoDB Command / Query
db.products.find({
$text: {
$search: "coding"
}
})
Expected Output
{
name: "Monitor",
description: "Large monitor for coding and office work"
}
Explanation
MongoDB searches the indexed text and returns documents containing the searched term.
Q5. Search for Multiple Words
Problem Statement
Find products containing either laptop or programming.
MongoDB Command / Query
db.products.find({
$text: {
$search: "laptop programming"
}
})
Expected Output
{
name: "Laptop",
description: "Powerful laptop for programming and data analysis"
}
Explanation
When multiple terms are supplied to $search, MongoDB performs a text search for those terms. Documents matching the search expression can be returned.
Q6. Search for an Exact Phrase
Problem Statement
Find products containing the exact phrase "data analysis".
MongoDB Command / Query
db.products.find({
$text: {
$search: "\"data analysis\""
}
})
Expected Output
{
name: "Laptop",
description: "Powerful laptop for programming and data analysis"
}
Explanation
Double quotes inside the search string are used to search for a phrase rather than treating the words independently.
Q7. Search Using a Text Index and Return Only Selected Fields
Problem Statement
Search for programmers and display only the product name and description.
MongoDB Command / Query
db.products.find(
{
$text: {
$search: "programmers"
}
},
{
_id: 0,
name: 1,
description: 1
}
)
Expected Output
{
name: "Keyboard",
description: "Mechanical keyboard for programmers"
}
Explanation
The second argument of find() is a projection. Here, _id is hidden and only name and description are displayed.
Q8. Search Text and Sort by Relevance Score
Problem Statement
Search for programming and sort the results according to MongoDB’s text relevance score.
MongoDB Command / Query
db.products.find(
{
$text: {
$search: "programming"
}
},
{
score: {
$meta: "textScore"
},
_id: 0,
name: 1,
description: 1
}
).sort({
score: {
$meta: "textScore"
}
})
Expected Output
{
name: "Laptop",
description: "Powerful laptop for programming and data analysis",
score: 1.5
}
Explanation
$meta: "textScore" provides MongoDB’s text relevance score. The exact score can vary depending on the data and search terms.
Q9. Create a Text Index on Multiple Fields
Problem Statement
Create a text index on both the name and description fields of the products collection.
MongoDB Command / Query
db.products.createIndex({
name: "text",
description: "text"
})
Expected Output
name_text_description_text
Explanation
A single text index can cover multiple fields. MongoDB can then search the indexed text across both name and description.
Important: A collection can have only one text index, but that text index can contain multiple fields.
Q10. View and Remove the Text Index
Problem Statement
First, display the indexes on the products collection. Then remove the text index named name_text_description_text.
MongoDB Command / Query
Check the indexes:
db.products.getIndexes()
Remove the text index:
db.products.dropIndex("name_text_description_text")
Expected Output
For getIndexes():
[
{
name: "_id_",
key: {
_id: 1
}
},
{
name: "name_text_description_text",
key: {
_fts: "text",
_ftsx: 1
}
}
]
For dropIndex():
{
nIndexesWas: 2,
ok: 1
}
Explanation
getIndexes() displays the indexes in the collection, while dropIndex() removes the specified text index.
Key Takeaways
- A Text Index is used for text searching in MongoDB.
- Create a text index using
"text"withcreateIndex(). - The
$textoperator performs a text search. $searchspecifies the word or phrase to search for.- A text index can cover multiple string fields.
- MongoDB allows only one text index per collection.
- Exact phrases can be searched using quotation marks inside
$search. $meta: "textScore"can be used to obtain text relevance scores.getIndexes()displays existing indexes.dropIndex()removes a specific text index.- Text indexes are different from normal ascending (
1) and descending (-1) indexes.
FAQs
1. What is a Text Index in MongoDB?
A Text Index is a special MongoDB index that allows efficient searching of words and phrases in string fields.
2. How do you create a Text Index in MongoDB?
Use createIndex() with the "text" index type:
db.products.createIndex({
description: "text"
})
3. How do you search using a Text Index?
Use the $text query operator with $search:
db.products.find({
$text: {
$search: "programming"
}
})
4. Can MongoDB search multiple fields using one Text Index?
Yes. You can create one text index covering multiple fields:
db.products.createIndex({
name: "text",
description: "text"
})
5. Can a MongoDB collection have multiple Text Indexes?
No. A collection can have only one text index, although that index can cover multiple fields.
6. What is textScore in MongoDB?
textScore is MongoDB’s relevance score for a text-search result. It can be accessed using:
{
score: {
$meta: "textScore"
}
}
7. How do you remove a Text Index in MongoDB?
Use dropIndex() with the index name:
db.products.dropIndex("name_text_description_text")
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
