0
0
MongoDBquery~30 mins

Text indexes for search in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Text Indexes for Search in MongoDB
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the $meta: "textScore" in projection and sort to show and order by relevance.