MongoDB Phrase Search Example
Let’s look at some examples of phrase search in MongoDB, to understand this concept better.
In the following examples, we are working with:
Database: gfg
Collection: content
Document: The content collection contains the three documents.
Find the Phrase Example
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 Exact Phrase Example
In 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:
MongoDB Text Search
MongoDB Text Search technique finds a piece of text or a specified word from the string fields. It enables users to search for specific words or phrases within text fields efficiently.
The text index and $text operator perform text search in MongoDB, providing a powerful way to search for textual data in MongoDB collections.
Contact Us