Exploring Full-Text Search in MongoDB
Learn how to perform full-text search in MongoDB to retrieve documents based on textual content.
Prerequisites
Before you begin, make sure you have the following prerequisites:
- MongoDB installed and running locally or accessible through a connection string.
- A collection with textual data to search within.
Step 1: Index Creation
Create a text index on the field you want to search. In this example, we'll create a text index on a "description" field:
// Create a text index on the "description" field
db.collection.createIndex({ description: "text" });
Step 2: Performing a Text Search
Perform a text search using the `$text` operator. Here's an example of a text search query:
// Perform a text search for the term "example"
db.collection.find({ $text: { $search: "example" } });
Step 3: Sorting and Scoring
By default, MongoDB returns results sorted by text score. You can also sort by other fields and assign a custom score to each document. Here's an example:
// Perform a text search with custom scoring and sorting
db.collection.find(
{ $text: { $search: "example" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" }, otherField: 1 });
Step 4: Text Index Configuration
You can configure text indexes to control language-specific behavior and other options. For example, to specify a language and disable stemming:
// Configure a text index with language and no stemming
db.collection.createIndex(
{ description: "text" },
{ default_language: "english", language_override: "language", textIndexVersion: 3 }
);
Conclusion
You've learned the basics of full-text search in MongoDB. This guide covers index creation, performing searches, sorting, scoring, and index configuration. With these foundational skills, you can explore more advanced text search features and implement full-text search in your MongoDB applications.