Text Search in MongoDB
Starting with version 2.4, MongoDB started supporting Text Indexes to search within the string content.
Starting with version 2.4, MongoDB started supporting Text Indexes to search within the string content. Text Search uses Stemming technique to search for specific words in string fields by deleting Stemming Word such as a, an, the, . Currently, MongoDB supports about 15 languages.
Enable Text Search in MongoDB
At first, Text Search was an experimental feature, but starting with version 2.6, the configuration is enabled by default. But if you are using a previous version of MongoDB, you need to activate Text Search with the following code:
> db . adminCommand ({ setParameter : true , textSearchEnabled : true })
Create Text Index in MongoDB
You follow the following Document under the collection posts containing post_text and its tags.
{ "post_text" : "enjoy the mongodb articles on tutorialspoint" , "tags" : [ "mongodb" , "tutorialspoint" ] }
We will create a Text Index on the post_text field so that we can search within the text section of posts:
> db . posts . ensureIndex ({ post_text : "text" })
Use Text Index in MongoDB
Now that you have created the Text Index on the post_text field, we will search all posts that are from tutorialspoint in their text:
> db . posts . find ({ $text :{ $search : "tutorialspoint" }})
The above command returns Documents with tutorialspoint in post_text:
{
"_id": ObjectId ("53493d14d852429c10000002"),
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": ["mongodb", "tutorialspoint"]
}
{
"_id": ObjectId ("53493d1fd852429c10000003"),
"post_text": "writing tutorials on mongodb",
"tags": ["mongodb", "tutorial"]
}
If you are using an older version of MongoDB, you must use the following command:
> db . posts . runCommand ( "text" ,{ search : " tutorialspoint " })
The use of Text Search significantly improves search efficiency when compared to regular search.
Delete Text Index in MongoDB
To delete an existing Text Index, first find the index's name using the query:
> db . posts . getIndexes ()
After taking the name of the index from the above query, run the following command. Here, post_text_text is the name of the index.
> db . posts . dropIndex ( "post_text_text" )
According to Tutorialspoint
Previous article: Map Reduce in MongoDB
Next post: Regular Expression in MongoDB
You should read it
- Index (Mong) in MongoDB
- Advantages of MongoDB
- MongoDB queries and tasks you should know
- Limitations of indexes in MongoDB
- Advanced index operation in MongoDB
- Instructions on 2 ways to install MongoDB on Raspberry Pi
- Covered Query in MongoDB
- Query analysis in MongoDB
- ObjectId in MongoDB
- Data type in MongoDB
- MongoDB malicious code attacks more than 26,000 victims in a week
- Query Document in MongoDB