MongoDB Text Search 

feature-image-mogodb-text-search.jpg

MongoDB is a NoSQL database that stores data in a flexible, document-based format. As the collection of the data grows, searching for a particular text in the large data becomes difficult. This problem is solved by using the MongoDB text search, which allows you to search for words and phrases based on relevance instead of exact matches. This is very helpful for searching the products, documents, and any feature where quick and meaningful results are expected. In this blog, you will understand what MongoDB text search is, its importance, and different ways to perform text search in MongoDB in detail.

 Table of Contents:

What is MongoDB Text Search and How Does It Work?

MongoDB text search is a function that is used to search for strings in a document that has text in it. This text search helps retrieve all related documents containing the given string, even if it doesn’t match all the strings given. It will give the result even if one word in the string matches in the document. For example, if we are searching for the string “Book”, the text string will fetch all the matches that relate to Book as well as the results that match, like “The Book Thief”, as The Book Thief contains the word ‘book’, and the text search identifies it as a match. 

Importance of Text Search in MongoDB

Let’s now understand the reason why the text search is very important in MongoDB:

  • Faster Searches: Text search uses a text index, so MongoDB finds results quickly even when the collection is huge.
  • Smarter Matching: It ignores case, understands word variations, and returns related results instead of relying on exact matches.
  • Search Across Fields: It can look through multiple text fields together, which makes it more useful than regex or basic query filters.
  • More Meaningful Results: It highlights documents that match the search terms closely, so users find what they’re looking for without digging through unrelated data.

How does the MongoDB Text Search Work?

It is very important to understand how the text search in MongoDB works before going into further detail. These steps show how the collection is created, how the sample data is inserted, how the text index is built, and finally run the search.

Step 1: Create the Collection and Insert Documents

Start by creating a collection and adding a few sample documents. This gives MongoDB some text fields to work with during the search.

Example:

db = client['mydatabase']
Intellipaat = db['Intellipaat']

Intellipaat.insert_many([
{
"title": "Wings of Fire",
"description": "It is a book about Dr. A.P.J. Kalam."
},
{
"title": "The Book Thief",
"description": "A story of a young girl and her love for books."
},
{
"title": "Introduction to Finance",
"description": "An article published by Intellipaat."
}
])

Explanation: Here, three documents are created wth the text fields in which the MongoDB can index and search.

Step 2: Create the Text Index

A text search will not work until the text index is built. This index stores the keywords from the selected fields, which helps MongoDB to find the matches quickly. Without it MongoDB would scan every document, which slows down the search.

Syntax:

db.collection.createIndex({ field1: "text", field2: "text" });

Example:

Intellipaat.create_index([
('title', 'text'),
('description', 'text')
])

Explanation: Here, the title and description fields are indexed. Once this index is ready, MongoDB can find words quickly without the need to scan the entire collection.

Now the actual text search is performed using the $text operator. This operator checks the text index for the matches.

Example:

query = { "$text": { "$search": "Book" } }

print("Documents matching 'Book':\n")
for doc in Intellipaat.find(query):
print(doc)

Output:

Working of MongoDB text search

Explanation: Here, this search returns all the documents where the word “Book” appears in the indexed field.

Master SQL & Elevate Your Career
Get lifetime access to expert-led lessons, real-world projects, and career-ready skills.
quiz-icon

Different Ways to Perform Text Search in MongoDB

MongoDB allows you to search text in different ways depending on the data and the result you need. You can look for a single word, find exact phrases, exclude certain terms, or even filter results using the query conditions. These methods make the text search very flexible and easy to use across different collections.

1. How to Search a Single Text in a MongoDB Collection

Once the text index is set, you can perform the text search using the MongoDB $text operator. The $text operator is a MongoDB search operator used to match text inside indexed fields. It allows you to quickly find documents that contain a specific word or phrase without scanning the entire collection.

Example:

db = client['mydatabase']
Intellipaat = db['Intellipaat']
Intellipaat.insert_many([
    {
        "title": "Wings of Fire",
        "description": "It is a book about Dr. A.P.J. Kalam."
    },
    {
        "title": "The Book Thief",
        "description": "A story of a young girl and her love for books."
    },
    {
        "title": "Introduction to Finance",
        "description": "An article published by Intellipaat."
    }
])
Intellipaat.create_index([('title', 'text'), ('description', 'text')])
query = { "$text": { "$search": "Book" } }
print("Documents matching 'Book':\n")
for doc in Intellipaat.find(query):
    print(doc)

Output:

MongoDBSearch a Single Text

Explanation: Here, all the text search results will be under the { }, and each will have its own index as _id as the text index.

Get 100% Hike!

Master Most in Demand Skills Now!

2. How to Perform Phrase Search in MongoDB

Phrase search is used when you want MongoDB to exactly match the particular phrase instead of finding individual words separately. To do this, the search term must be written inside double quotes so that MongoDB treats the whole text as one unit.

Example:

db = client['mydatabase']
Intellipaat = db['Intellipaat']

Intellipaat.drop()
Intellipaat.insert_many([
{
"title": "Full-Text Search in Databases",
"content": "Databases use text indexes to perform search operations."
},
{
"title": "Text and Search Basics",
"content": "Basic concepts of text search functionalities."
},
{
"title": "Learn to Cook Easily",
"content": "Easy way of Learning Cooking."
}
])
Intellipaat.create_index([('title', 'text'), ('content', 'text')])

query = {
"$text": { "$search": "\"text search\"" }
}
results = Intellipaat.find(query)
for doc in results:
print(doc)

Output:

phrase search mongodb

Explanation: Here, the MongoDB matches only the documents that contain the exact phrase “text search” in the same order. It treats the phase inside the quote as a single unit, so on the documents with the full phase are returned.

3. How to Remove or Exclude Strings While Text Searching in MongoDB

Sometimes you may want MongoDB to find documents that contain one word but ignore another word in the same search.

For example, “Python-SQL” will search for the word Python but exclude the word SQL.

db = client['mydatabase']
Intellipaat = db['Intellipaat']
Intellipaat.insert_many([
    { "title": "Learn Python", "content": "Learn Python Easily." },
    { "title": "History of SQL and Python", "content": "History and integration of SQL and Python." },
    { "title": "Python for Data Science", "content": "Python is used in machine learning." },
    { "title": "Basics of SQL", "content": "Learn database management." },
])
Intellipaat.create_index([('title', 'text'), ('content', 'text')])
query = { "$text": { "$search": "Python -SQL" } }
results = Intellipaat.find(query)
for Intellipaat in results:
    print(Intellipaat)

Output:

MongoDBExcluding Strings While Searching

Explanation: Here, the $search found the output for Python and eliminated the output that has SQL in it. 

4. How to Search Text Using Query Operators in MongoDB

These query operators in NoSQL are queries that are used to fetch the text string based on a condition, like the “WHERE” or “IN” operator in SQL. There are some query operators like $gt, $lt, and $in that are filters that are used to search the text string with conditions. 

Example:

from datetime import datetime
from pymongo import MongoClient
db = client['mydatabase']
articles = db['articles']
articles.drop()
articles.insert_many([
    {
        "title": "Introduction to MongoDB",
        "content": "MongoDB is a NoSQL database.",
        "publishedDate": datetime(2023, 7, 19)
    },
    {
        "title": "Advanced MongoDB Queries",
        "content": "Learn about queries in MongoDB.",
        "publishedDate": datetime(2023, 6, 24)
    },
    {
        "title": "Basics of SQL Databases",
        "content": "Learn SQL database.",
        "publishedDate": datetime(2022, 2, 27)
    },
    {
        "title": "MongoDB or SQL",
        "content": "Difference between MongoDB and SQL databases.",
        "publishedDate": datetime(2022, 1, 3)
    },
    {
        "title": "Learn Web Development",
        "content": "All-Rounder for web development.",
        "publishedDate": datetime(2023, 2, 1)
    }
])
articles.create_index([('title', 'text'), ('content', 'text')])
query = {
    "$text": {"$search": "MongoDB"},
    "publishedDate": {"$gt": datetime(2023, 1, 1)}
}
results = articles.find(query)
for doc in results:
    print(doc)

Output:

Searching Text With Query Operators

Explanation: Here, the $gt fetched only the document that has a publish date in the year 2023. 

These key points help in improving MongoDB search performance, especially when working with large collections.

  1. The size of each index in the database requires more space in the database, which may affect the performance and storage.
  2. Text search will perform slower than exact matching queries, as the text search will result in all the relevant searches in the database. 
  3. Text indexes are less efficient with high-cardinality fields (many unique words). Avoid indexing fields with highly variable vocabulary unless needed.
  4. MongoDB’s default text index ignores common stop words (e.g., “the”, “and”). It also applies stemming, which may match variations (e.g., “run”, “running”).

Limitations of Text Index in MongoDB

Now, let’s explore the limitations of text indexing in MongoDB.

  • Each collection can have only one text index, but that index can cover multiple fields.
  • Adding the text string may increase the size of the database, which will reduce the write performance of the database. 
  • Only strings or arrays of string values in indexed fields are considered during text search. 
  • Text indexes do not support sorting on fields other than the relevance score (textScore) without using a compound index. 

Best Practices for Text Search in MongoDB

Now, let’s explore the best practices of text indexing in MongoDB.

  1. Always index only the fields you need for text search. This helps MongoDB run the search faster.
  2. Try to limit the number of search results. This will reduce the memory usage. 
  3. Text searches are always case-insensitive. So words match even if the letter cases are different.
  4. MongoDB text search always ignores the common words when searching, like the, is, or, from, that, etc.
  5. Use compound indexes when searching multiple fields to improve query efficiency and relevance.
Learn SQL for Free – Start Today!
No sign-up fees. Just pure, practical SQL skills to kickstart your data journey. Beginner-friendly and 100% free.
quiz-icon

Conclusion

Text Search is one of the essential tools in MongoDB that helps to search for text strings without any need to install search engines or integration tools. By learning to use text search, you can effectively apply search conditions to filter results based on your specific criteria. By understanding the basic structure and performance, you can easily search for any text string efficiently.

Upskill today by enrolling in our MongoDB Course, and also prepare for your next interview with MongoDB Interview Questions prepared by industry experts.

MongoDB Text Search – FAQs

Q1. How to search for text in MongoDB?

To search text in MongoDB, create a text index on the desired fields and use the $text operator with the $search keyword to find matching documents.

Q2. How do I create a text search index in MongoDB?

Use db.collection.createIndex({ field: “text” }) to create a text index in MongoDB.

Q3. How to use $text in MongoDB?

Query with { $text: { $search: “your search string” } } to find matching documents in MongoDB.

Q4. What is text-based search?

Text-based search retrieves documents based on matching keywords or phrases in text fields.

Q5. Is MongoDB good for full-text search?

MongoDB is good for basic full-text search, but for advanced needs, tools like Elasticsearch are better.

Q6. Can MongoDB text search handle multiple fields at once?

Yes, MongoDB can search across multiple fields at the same time when you create a text index on all the required fields.

Q7. How to optimize MongoDB text search for better performance?

Focus only on the fields you need, limit the results, and use compound indexes to keep MongoDB text search fast and efficient.



About the Author

Technical Writer | Business Analyst

Yash Vardhan Gupta is an expert in data and business analysis, skilled at turning complex data into clear and actionable insights. He works with tools like Power BI, Tableau, SQL, and Markdown to develop effective documentation, including SRS and BRD. He helps teams interpret data, make informed decisions, and drive better business outcomes. He is also passionate about sharing his expertise in a simple and understandable way to help others learn and apply it effectively.

business intelligence professional