![]() |
VOOZH | about |
MongoDB Text Search is a powerful feature designed to find specified text within string content in MongoDB collections. This capability is essential for applications that require efficient and effective searching capabilities. Text indexes in MongoDB should be strings or arrays of string elements and each collection can contain only one text index though this index can cover multiple fields.
In this article, We will learn about MongoDB Text Search capabilities with clear explanations and real-world examples.
MongoDB Text Search allows searching for specific text values in documents stored within a collection. When we perform a text search query always remember that our collection must contain a text index and a collection can only contain one text index but this single text index covers multiple fields. To create a text index in MongoDB use the createIndex() method.
Syntax
db.collectionName.createIndex( { field: βtextβ } )
The $text operator in MongoDB is used to search the text index. This operator performs text search operations on the collection with a text index. This operator tokenizes each search string with whitespace and treats most punctuations as delimiters except - and \". After tokenizing the search string it performs a logical OR operation on the tokens. If we want to sort the resultant documents then use the $meta query operator.
Syntax:
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
Key Terms
MongoDB Text Search is an essential feature that allows efficient searching of text-based content within a collection. Below are the steps to perform text search in MongoDB:
In the following example, we are working with:
Now we create a string index on the name and pet field with the help of the createIndex() method. So we can search text over the name and line fields:
Query:
db.content.createIndex({name:"text",line:"text"})Output:
π create indexNow we are ready to search text. For example, we are going to search all the document which contain text love.
Query:
db.content.find({$text:{$search:"love"}}) Note: $text is a query operator that performs text searches on a collection with a text index.
Output:
π text search in mongodbOne more example in which we are going to search all the document which contain dog text:
Query:
db.content.find({$text:{$search:"dog"}})Output:
π text search in mongodb example outputInstead of searching a single word you are also allowed to search for a phrase by wrapping the phrase in double quotes(""). Generally, the phrase search performs OR operation in between the specified keywords.
For example, the phrase is "I like Mango", then phase search looks for all the documents that contain keywords either I, like, or Mango. And if you want to perform an exact phrase search then wrap the phase in between escaped double quotes(\").
db.collectionName.find({$text:{$search:"Phrase"}})
db.collectionName.find({$text:{$search:"\"Phrase"\"}})
To understand how phrase search works in MongoDB, let's consider the following setup:
gfgcontentcontent collection contains three documents with text-based data.In the examples below, we will perform a phrase search to find documents that contain specific phrases using MongoDB's $text operator. We'll also explore how to perform exact phrase searches by wrapping the phrase in escaped double quotes (\" \").
In this example, we search for the phrase "I love dogs". So, in the result, we get all the documents that contain keywords I, love, or dogs.
Query:
db.content.find({$text:{$search:"I love dogs"}})Output:
π find the phrase exampleIn this example, we search for the exact phrase by wrapping the phase in between escaped double quotes(\").i.e., "\"I love dogs\"". So, in the result, we only get those documents that contain the specified exact phrase
Query:
db.content.find({$text:{$search:"\"I love dogs\""}})Output:
π find exact phrase example outputExclusion of term means when you perform search operation and do not want to display the document that contains the specified term, so you can exclude the term by prefixing a search keyword with the minus sign(-).
Using minus sign(-) you can exclude all the documents that contain excluded term. For example, you want to display all the documents that contain the keyword "Car" but not the "Cycle" keyword so you can use the following query:
dn.collectionName.find({$text:{$search:"Car -Cycle"}})To better understand how to exclude a specific term from text search in MongoDB, let's consider the following scenario:
gfgcontentcontent collection contains three documents with text-based data.In the example below, we will perform a text search to find documents containing a specific keyword while excluding another keyword using the - (minus) operator.
In this example, we only display those documents that contain dog not cow
Query:
db.content.find({$text:{$search:"dog -cow"}})Output:
π outputWe can search text using the aggregation pipeline with the help of the $text query operator in the $match stage. But there are some restrictions for using the $text operator:
Note: Text score is a score that is assigned to each document that holds the search term in the index field by the $text operator. The score reflects a document's importance to a given text search query.
Let's consider a MongoDB database named gfg, which contains a collection called people. The people collection consists of five documents, each representing a person with various attributes such as name, age, and pet preferences.
We will use MongoDBβs aggregation pipeline to perform text search operations on this collection.
π demo mongodb database and collectionIn this example, we count the number of the document in which pet value is a cat:
Query:
db.people.aggregate([{$match:{$text:{$search:"Cat"}}},
{$group:{_id:null,total:{$sum:1}}}])
Output:
π example 1 outputIn this example, we count the number of the document in which pet value is a dog:
Query:
db.people.aggregate([{$match:{$text:{$search:"Dog"}}},
{$group:{_id:null,total:{$sum:1}}}])
Output:
π example 2 outputIn this example, we return the Sorted result by using text score. We return the result(all the documents that contain the specified text,i.e., "Dog") in the sorted form using textScore
Query:
db.people.aggregate([{$match:{$text:{$search:"Dog"}}},
{$sort:{score:{$meta:"textScore"}}},
{$project:{_id:0,name:1}}])
Output:
π example 3 outputMongoDB Text Search is a powerful feature that enables full-text search capabilities in NoSQL databases. By creating text indexes and using the $text operator, developers can efficiently perform word searches, phrase searches, and exclusions. Additionally, text search can be integrated into MongoDBβs aggregation pipeline for advanced data processing. Mastering these techniques can enhance search performance and improve data retrieval in applications like e-commerce, document management, and search engines