📖 Scenario: You are building a simple book catalog for a local library. The library wants to allow users to search for books by keywords in the title and description.
🎯 Goal: Create a MongoDB collection with book documents, add a text index on the title and description fields, and perform a text search query to find books matching a keyword.
📋 What You'll Learn
Create a collection called books with at least three book documents containing title and description fields.
Create a text index on the title and description fields.
Write a query to find books matching the keyword adventure using the text index.
💡 Why This Matters
🌍 Real World
Text search indexes are used in many applications like libraries, e-commerce, and blogs to let users quickly find relevant content by keywords.
💼 Career
Knowing how to create and query text indexes in MongoDB is valuable for backend developers and data engineers working with search features.
Progress0 / 4 steps
1
Create the books collection with sample documents
Insert three documents into the books collection with these exact fields and values: { title: "The Great Adventure", description: "An exciting journey through mountains." }, { title: "Cooking Basics", description: "Learn simple recipes for beginners." }, and { title: "Mystery of the Old House", description: "A thrilling mystery novel." }.
MongoDB
Hint
Use db.books.insertMany([...]) to add multiple documents at once.
2
Create a text index on title and description
Create a text index on the title and description fields of the books collection using db.books.createIndex.
MongoDB
Hint
Use db.books.createIndex({ title: "text", description: "text" }) to create the text index.
3
Write a text search query for the keyword adventure
Write a query using db.books.find with { $text: { $search: "adventure" } } to find books matching the keyword adventure.
MongoDB
Hint
Use db.books.find({ $text: { $search: "adventure" } }) to perform the text search.
4
Add projection to show text score and sort by relevance
Modify the text search query to include a projection that adds score: { $meta: "textScore" } and sort the results by { score: { $meta: "textScore" } } to show the most relevant books first.
MongoDB
Hint
Use find(query, projection) and sort() with { $meta: "textScore" } to show relevance.
Practice
(1/5)
1. What is the main purpose of creating a text index in MongoDB?
easy
A. To store large text files efficiently
B. To speed up searching for words in text fields
C. To encrypt text fields for security
D. To sort documents by text fields alphabetically
Solution
Step 1: Understand what a text index does
A text index allows MongoDB to quickly search for words inside text fields instead of scanning all documents.
Step 2: Compare options with the purpose
Only To speed up searching for words in text fields matches the purpose of speeding up word searches. Other options describe unrelated features.
Final Answer:
To speed up searching for words in text fields -> Option B
Quick Check:
Text index purpose = speed up word search [OK]
Hint: Text indexes help find words fast in text fields [OK]
Common Mistakes:
Confusing text index with sorting index
Thinking text index encrypts data
Assuming text index stores files
2. Which of the following is the correct syntax to create a text index on the field description in MongoDB?
easy
A. db.collection.createIndex({ description: 1 })
B. db.collection.createIndex({ description: 'string' })
C. db.collection.createTextIndex({ description: 1 })
D. db.collection.createIndex({ description: 'text' })
Solution
Step 1: Recall the syntax for text index creation
The correct syntax uses createIndex with the field set to the string 'text'.
Step 2: Check each option
db.collection.createIndex({ description: 'text' }) matches the correct syntax. db.collection.createIndex({ description: 'string' }) uses 'string' which is invalid. db.collection.createTextIndex({ description: 1 }) uses a non-existent method. db.collection.createIndex({ description: 1 }) creates a normal ascending index, not text.
Final Answer:
db.collection.createIndex({ description: 'text' }) -> Option D
Quick Check:
Text index syntax = createIndex({field: 'text'}) [OK]
Hint: Use createIndex with 'text' to make text indexes [OK]
Common Mistakes:
Using 'string' instead of 'text'
Using createTextIndex method (doesn't exist)
Creating normal indexes instead of text indexes
3. Given a collection with a text index on the field content, what will the following query return?
A. Documents containing either 'mongodb' or 'tutorial' in the content field
B. Documents containing both words 'mongodb' and 'tutorial' in the content field
C. Documents containing the exact phrase 'mongodb tutorial' only
D. Documents sorted alphabetically by content
Solution
Step 1: Understand $text and $search behavior
The $search operator looks for documents containing any of the words listed, not necessarily all or exact phrases.
Step 2: Analyze the options
Documents containing either 'mongodb' or 'tutorial' in the content field correctly states it returns documents containing either word. Documents containing both words 'mongodb' and 'tutorial' in the content field requires both words, which is not default. Documents containing the exact phrase 'mongodb tutorial' only requires exact phrase, which needs quotes. Documents sorted alphabetically by content is unrelated.
Final Answer:
Documents containing either 'mongodb' or 'tutorial' in the content field -> Option A
Quick Check:
$search finds any listed words by default [OK]
Hint: By default, $search matches any listed words [OK]
Common Mistakes:
Assuming $search matches all words by default
Thinking $search matches exact phrases without quotes
Confusing search results with sorting
4. You run this query but get an error:
db.posts.find({ $text: { $search: "database" } })
What is the most likely cause?
medium
A. The query syntax requires parentheses
B. The $search operator is misspelled
C. No text index exists on the collection
D. The field name 'database' is invalid
Solution
Step 1: Understand requirements for $text queries
MongoDB requires a text index on at least one field to use $text queries without error.
Step 2: Check the options for likely causes
No text index exists on the collection correctly identifies missing text index as the cause. Other options describe syntax or spelling errors which are not present.
Final Answer:
No text index exists on the collection -> Option C
Quick Check:
$text query needs text index [OK]
Hint: Ensure text index exists before using $text queries [OK]
Common Mistakes:
Ignoring the need for a text index
Thinking $search syntax is wrong
Assuming field names cause $text errors
5. You want to find documents that contain the exact phrase "fast search" in the summary field which has a text index. Which query will correctly do this?
hard
A. db.collection.find({ $text: { $search: '"fast search"' } })
B. db.collection.find({ $text: { $search: 'fast search' } })
C. db.collection.find({ summary: { $regex: 'fast search' } })
D. db.collection.find({ $text: { $search: '\"fast search\"' } })
Solution
Step 1: Recall how to search exact phrases with $text
Exact phrase search requires double quotes around the phrase inside the $search string.
Step 2: Evaluate each option
db.collection.find({ $text: { $search: '"fast search"' } }) correctly uses single quotes outside and double quotes inside to search exact phrase. db.collection.find({ $text: { $search: 'fast search' } }) searches words separately. db.collection.find({ summary: { $regex: 'fast search' } }) uses regex, not text search. db.collection.find({ $text: { $search: '\"fast search\"' } }) escapes quotes incorrectly.