How to Perform Text Search MongoDB
MongoDB Text Search operation is very important operation :
Step 1: First, we create a collection and add some documents to the collection:
In the following example, we are working with:
Database: gfg
Collection: content
Document: The content collection contains the three documents.
Step 2: Create index
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:
Step 3: Search Text
Now 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:
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