0
0
MongoDBquery~30 mins

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

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

Use find(query, projection) and sort() with { $meta: "textScore" } to show relevance.