MongoDB - Text Search

Starting with version 2.4, MongoDB started supporting text indexes for searching inside string content. Text search uses stemming methods to search for specified words in string fields by removing words like a, an, the, etc. MongoDB currently supports about 15 languages.
Enable text search
Initially, text search was an experimental feature, but as of version 2.6, the configuration is enabled by default. But if you are using the previous version of MongoDB, then you have to enable text search with the help of the following code −
> db . adminCommand ({ setParameter : true , textSearchEnabled : true })
Create a text index
Consider the following document under the message collection , containing the body of the message 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 inside the text of our posts −
> db . posts . ensureIndex ({ post_text : "text" })
Using a text pointer
Now that we've created a text index on the post_text field, we'll look for all posts that have the word tutorialspoint in their text.
> db . posts . find ({ $text :{ $search : "tutorialspoint" }})
The above command returned the following result documents having the word tutorialspoint in their message body −
{ "_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 old versions of MongoDB, then you should use the following command −
> db . posts . runCommand ( "text" ,{ search : "tutorialspoint " })
The use of text search greatly improves search efficiency compared to conventional search.
Deleting a text pointer
To delete an existing text index, first find the index name using the following query −
> db . posts . getIndexes ()
After getting your index name from the above query, run the following command. Here post_text_text is the name of the index.