📖 Scenario: You are building a simple book catalog database for a local library. The library wants to allow users to search for books by their title and description quickly.
🎯 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 search term.
📋 What You'll Learn
Create a collection named books with documents containing title and description fields.
Add a text index on the title and description fields.
Write a query to search the books collection using the text index for a given search term.
💡 Why This Matters
🌍 Real World
Text indexes in MongoDB are used in many applications like search engines, e-commerce product search, and content management systems to quickly find relevant documents based on keywords.
💼 Career
Knowing how to create and use text indexes is important for database developers and backend engineers to optimize search functionality and improve user experience.
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 Gatsby", description: "A novel set in the Jazz Age." }, { title: "Moby Dick", description: "A story about a giant whale." }, and { title: "Hamlet", description: "A Shakespearean tragedy." }.
MongoDB
Hint
Use insertMany to add multiple documents to the books collection.
2
Create a text index on title and description
Create a text index on the books collection for the fields title and description using db.books.createIndex with the correct syntax.
MongoDB
Hint
Use createIndex with an object specifying "text" for both title and description.
3
Write a text search query for the term whale
Write a query using db.books.find with { $text: { $search: "whale" } } to find books that match the word whale in the text indexed fields.
MongoDB
Hint
Use $text operator with $search to perform the text search.
4
Add projection to show text search score
Modify the previous query to include a projection that adds the text search score as score using { score: { $meta: "textScore" } } and sort the results by score descending.
MongoDB
Hint
Use the $meta: "textScore" in projection and sort to show and order by relevance.
Practice
(1/5)
1. What is the main purpose of creating a text index in MongoDB?
easy
A. To encrypt text data for security
B. To enable fast searching of text within string fields
C. To store large text files inside the database
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 text inside string fields of documents.
Step 2: Compare options with the purpose
Sorting, storing files, or encrypting are not functions of text indexes.
Final Answer:
To enable fast searching of text within string fields -> Option B
Quick Check:
Text index = fast text search [OK]
Hint: Text index = fast search inside text fields [OK]
Common Mistakes:
Confusing text index with sorting index
Thinking text index stores files
Assuming text index encrypts data
2. Which of the following is the correct syntax to create a text index on the description field in a MongoDB collection named products?
easy
A. db.products.createTextIndex({ description: 1 })
B. db.products.createIndex({ description: 'string' })
C. db.products.createIndex({ description: 'text' })
D. db.products.createIndex({ description: 1 })
Solution
Step 1: Recall the syntax for creating a text index
The correct method is createIndex with the field set to 'text' type.
Step 2: Check each option
db.products.createIndex({ description: 'text' }) uses createIndex with { description: 'text' }, which is correct. Others use wrong methods or types.
Final Answer:
db.products.createIndex({ description: 'text' }) -> Option C
Quick Check:
Use createIndex with 'text' type [OK]
Hint: Use createIndex({field: 'text'}) to make text index [OK]
Common Mistakes:
Using 'string' instead of 'text' for index type
Using createTextIndex (not a valid method)
Creating normal ascending index (1) instead of text
3. Given a collection articles with a text index on fields title and content, what will the following query return?
A. Documents containing both words 'mongodb' and 'tutorial' in title or content
B. Documents containing exactly the phrase 'mongodb tutorial' only
C. Documents containing either 'mongodb' or 'tutorial' in any field
D. Documents sorted alphabetically by title
Solution
Step 1: Understand $text and $search behavior
The $search operator looks for documents containing all search words (AND behavior) in indexed text fields.
Step 2: Analyze the query
The query searches for documents with both 'mongodb' and 'tutorial' in either title or content fields.
Final Answer:
Documents containing both words 'mongodb' and 'tutorial' in title or content -> Option A
Quick Check:
$search finds all words, not exact phrase [OK]
Hint: $search finds all words, not exact phrase [OK]
Common Mistakes:
Thinking $search matches exact phrase only
Assuming $search matches any single word (OR)
Expecting sorting by title automatically
4. You tried to create two text indexes on a collection: one on title and another on description. What is the problem with this approach?
medium
A. MongoDB allows only one text index per collection
B. Text indexes must be created on numeric fields only
C. You must create text indexes using createTextIndex method
D. Text indexes cannot be created on multiple fields
Solution
Step 1: Recall MongoDB text index limitation
MongoDB allows only one text index per collection, but it can cover multiple fields.
Step 2: Evaluate the options
MongoDB allows only one text index per collection correctly states the limitation. Others are incorrect about field types or methods.
Final Answer:
MongoDB allows only one text index per collection -> Option A
Quick Check:
One text index per collection rule [OK]
Hint: Only one text index allowed per collection [OK]
Common Mistakes:
Trying to create multiple text indexes on same collection
Using wrong method name for creating text index
Thinking text indexes only work on numbers
5. You want to create a text index on title and summary fields but give title twice the search weight of summary. Which is the correct way to create this weighted text index?