MongoDB Text Search with the $text Operator
MongoDB text search lets you search string content in a collection by creating a text index and querying it with the $text operator. It is useful when you want to find documents that contain words or phrases in fields such as titles, descriptions, comments, article bodies, tags, or product summaries.
To do MongoDB Text Search, MongoDB provides $text query operator. $text query operator works in conjunction with text indexed fields.
In this tutorial, we will learn how to perform text based search in a MongoDB Collection, create a text index, prepare search strings, sort by text score, and understand the common limitations of MongoDB text search.
When to Use MongoDB Text Search
Use MongoDB text search when you need word-based matching on text fields. For example, you may search tutorial titles, blog descriptions, product names, support tickets, or knowledge base articles.
- Search documents by one or more words.
- Search exact phrases by enclosing the phrase in escaped double quotes.
- Exclude words by prefixing them with a minus sign.
- Rank matching documents using the text score returned by MongoDB.
MongoDB $text search is not the same as substring search. If you need prefix matching, wildcard matching, autocomplete, fuzzy search, or advanced relevance tuning, consider a different search approach such as regular expressions for simple patterns or MongoDB Atlas Search for richer full-text search use cases. You can refer to the MongoDB manual on text search for the current reference behavior.
Example – Text Search in MongoDB
Following is a step by step guide to perform MongoDB Text Search in a MongoDB Collection.
1. Create Sample Text Fields in MongoDB Collection
Please make a note that text search can be done only on text indexed fields.
For this example we shall use webpages collection. You may create it using the following command.
db.webpages.insert(
[
{ _id: 1, title: "Java Tutorial", description: "Learn with Java Example Programs" },
{ _id: 2, title: "Node Tutorial", description: "Learn server side programming" },
{ _id: 3, title: "MongoDB Tutorial", description: "Welcome to MongoDB Database" },
{ _id: 4, title: "Python Tutorial", description: "Learn Python programming" },
{ _id: 5, title: "Kotlin Tutorial", description: "Learn Kotlin programming" }
]
)
The collection contains two text fields, title and description. We will create a text index on these fields and then search inside them.
2. Create a MongoDB Text Index on Searchable Fields
Text search queries can be done on fields that has string content or array of strings. Create an index with those fields on which you would like to perform the search.
db.webpages.createIndex( { title: "text", description: "text" } )
> db.webpages.createIndex( { title: "text", description: "text" } )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Note : Make sure not to add every necessary and unnecessary field to the index. Add only those that you deem to be necessary. Number of fields in the index affect the overhead on the collection to reindex when there is a modification to the Collection.
In a collection, choose only the fields users are expected to search. For a tutorial page collection, title and description are reasonable search fields. For a product collection, you may choose fields such as name, summary, and category.
3. Prepare Search Items for MongoDB $search
Multiple elements which needs to be searched could be included in the search items.
Following table gives an idea of how to prepare search items.
| Search Items | Description |
| “item_1 item_2 item_3” | The three items are considered different and affect the text matching score individually and positively. |
| “item_1 item_2 -item_3” | Those field values that has item_3, would be excluded in the result. |
| “item_1 /”item_2 tem_3/”” | “item_2 item_3” is considered a single item. |
> var searchItems = "database mongodb";
The value passed to $search is a string. MongoDB parses this string and searches for matching terms in the text index. The examples below show common search string patterns.
| MongoDB $search string | Meaning |
|---|---|
"mongodb database" | Searches for documents that match the words mongodb or database, with scoring based on relevance. |
"mongodb -python" | Searches for mongodb and excludes documents that contain python. |
"\"server side\"" | Searches for the exact phrase server side. |
"programming tutorial" | Searches for either word and ranks stronger matches higher. |
4. Run MongoDB Text Search Query with $text
$text query operator is used to search the collection in the text indexed fields for the search items.
Following is the command bringing everything needed together for $text query operation
db.collection.find( { $text: { $search: searchItems } } )
> db.webpages.find( { $text: { $search: searchItems } } )
{ "_id" : 3, "title" : "MongoDB Tutorial", "description" : "Welcome to learn MongoDB Database" }
The query searches the text index created on title and description. MongoDB returns documents whose indexed text content matches the search string.
MongoDB Text Search Query Syntax
The basic syntax of a MongoDB text search query is shown below.
db.collection.find({
$text: {
$search: "search terms"
}
})
You may also pass additional options such as language, case sensitivity, and diacritic sensitivity when your use case needs them.
db.collection.find({
$text: {
$search: "search terms",
$language: "english",
$caseSensitive: false,
$diacriticSensitive: false
}
})
Return MongoDB Text Search Score
MongoDB can return a text score for each matching document. This score indicates how relevant the document is for the search string. To include the score in the result, use the $meta: "textScore" expression in the projection.
db.webpages.find(
{ $text: { $search: "mongodb database" } },
{ score: { $meta: "textScore" }, title: 1, description: 1 }
)
This query returns the matching documents along with a score field. The score is computed by MongoDB based on how well each document matches the search terms.
Sort MongoDB Text Search Results by Relevance
When multiple documents match a text search, sort the results by text score to show the most relevant documents first.
db.webpages.find(
{ $text: { $search: "tutorial programming" } },
{ score: { $meta: "textScore" }, title: 1, description: 1 }
).sort({ score: { $meta: "textScore" } })
Sorting by text score is useful in search pages because the best matches appear before weaker matches.
Search an Exact Phrase in MongoDB Text Search
To search an exact phrase, include the phrase inside escaped double quotes within the search string. The example below searches for the phrase server side.
db.webpages.find({
$text: {
$search: "\"server side\""
}
})
In the sample collection, this phrase appears in the description of the Node tutorial document.
Exclude a Word from MongoDB Text Search Results
Prefix a word with a minus sign to exclude documents that contain that word. The following query searches for tutorial but excludes documents that contain python.
db.webpages.find({
$text: {
$search: "tutorial -python"
}
})
This type of search is useful when a word has broad matches and you want to remove a known unwanted topic from the result set.
MongoDB Text Search with Case and Diacritic Options
By default, text search behavior depends on the text index and language rules. You can explicitly request case-sensitive or diacritic-sensitive matching when required. Most simple application searches keep both options as false.
db.webpages.find({
$text: {
$search: "MongoDB",
$caseSensitive: false,
$diacriticSensitive: false
}
})
Use these options carefully because stricter matching can reduce the number of returned documents.
MongoDB Text Search Limitations to Remember
MongoDB text search is practical for basic word-based matching, but it has limits. Understanding these limits helps you choose the right search design before building a production feature.
- A
$textquery requires a text index. - Text search is word-based; it is not designed for general substring matching.
- Prefix and wildcard search are not handled like autocomplete search.
- Adding too many fields to a text index increases index maintenance overhead.
- For advanced search features such as fuzzy matching, synonyms, highlighting, and autocomplete, review MongoDB Atlas Search or a dedicated search engine.
MongoDB Text Search Checklist
- Create a text index before using the
$textoperator. - Index only the fields that users need to search.
- Test simple word search, exact phrase search, and excluded word search separately.
- Project
textScorewhen the application needs relevance ranking. - Do not use
$textas a replacement for substring, wildcard, or autocomplete search.
FAQs on MongoDB Text Search
What is MongoDB text search?
MongoDB text search is a word-based search feature that uses a text index and the $text operator to find documents containing matching text in indexed string fields.
Does MongoDB text search need an index?
Yes. A $text query works only when the collection has a text index on the fields you want to search.
Can MongoDB text search find partial words?
MongoDB $text search is not intended for general partial-word or substring matching. For simple pattern matching, you may use regular expressions. For autocomplete or advanced search behavior, consider Atlas Search.
How do you sort MongoDB text search results by relevance?
Use { score: { $meta: "textScore" } } in the projection and sort with .sort({ score: { $meta: "textScore" } }). This places stronger text matches before weaker matches.
Can one MongoDB text index include multiple fields?
Yes. A text index can include multiple fields, as shown with title and description in this tutorial. Choose fields carefully to avoid unnecessary index overhead.
Summary of MongoDB Text Search Example
In this MongoDB Tutorial, we have learnt to do a text search in a MongoDB Collection with example. We created a text index, used the $text operator with $search, searched words and phrases, excluded unwanted terms, returned text scores, and sorted matching documents by relevance.
TutorialKart.com