Enable text Search:
The initial text search is an experimental feature, but the 2.6 version starts with the configuration enabled by default. However, if you are using a previous MongoDB version, you must enable text search, using the following code:
>db. Admincommand({setparameter:true,textsearchenabled:True})
To create a text index:
Consider the post collection for which the text is tagged, including the following files:
{ "Post_text":"Enjoy the MongoDB articles on Yiibai","tags":["MongoDB" ,"Yiibai"]}
We will create a text index of the Post_text field so that we can search for text in our posts:
>db. Posts. Ensureindex({post_text:"text"})
Use a text index:
Now that we have created the index of the text Post_text field, we will search for all posts that contain the word yiibai.com.
>db. Posts. Find({$text: {$search:"yiibai.com"}})
The above command returns a post that contains yiibai words in the text, such as the following result document:
{ "_id": ObjectId ("53493d14d852429c10000002"), "Post_text": "Enjoy the MongoDB articles on yiibai.com", " Tags ": [" MongoDB "," yiibai.com "]}{ " _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:"yiibai.com"})
The use of text search is much more efficient than regular search.
To delete a text index:
To delete an existing text index, use the following query to first find the name of the index:
>db. Posts. Getindexes()
After you get 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")
MongoDB Text Index