The full-text index sets up each word in an indexed, indicating the number and location of occurrences of the word in the article, and when the user queries, the retrieval program searches based on the pre-established index and feeds the results back to the user's search method.
This process is similar to the process of looking up a word in a dictionary using the search Word table.
MongoDB supports full-text indexing starting with version 2.4 and currently supports full-text indexes in 15 languages (Chinese is temporarily not supported).
- Danish
- Dutch
- 中文版
- Finnish
- French
- German
- Hungarian
- Italian
- Norwegian
- Portuguese
- Romanian
- Russian
- Spanish
- Swedish
- Turkish
Enable full-Text indexing
MongoDB turns on full-text indexing by default after version 2.6, and if you use previous versions, you need to use the following code to enable full-text indexing:
>db.admincommand ({setparameter:true,textsearchenabled:true})
or use the command:
Mongod--setparameter Textsearchenabled=true
To create a full-text index
Consider the following posts collection of document data, including the article content (Post_text) and tags (tags):
{ "Post_text": "Enjoy the MongoDB articles on w3cschool.cn", "tags": [ "MongoDB", "W3cschool" ]}
We can create a full-text index of the Post_text field so that we can search for content within the article:
>db.posts.ensureindex ({post_text: "text"})
Using Full-Text indexing
Now that we have a full-text index on Post_text, we can search for the keyword w3cschool.cn in the article:
>db.posts.find ({$text: {$search: "w3cschool.cn"}})
The following command returns the following document data containing the W3CSCHOOL.CN keyword:
{ "_id": ObjectId ("53493d14d852429c10000002"), "Post_text": "Enjoy the MongoDB articles on w3cschool.cn", "tags": ["MongoDB", "W3cschool"]} { "_id": ObjectId ("53493d1fd852429c10000003"), "Post_text": "Writing tutorials on w3cschool.cn", "tags ": [" MongoDB "," Tutorial "]}
If you are using an older version of MongoDB, you can use the following command:
>db.posts.runcommand ("text", {search: "w3cschool.cn"})
Using full-text indexing can improve search efficiency.
To delete a full-text index
To delete a full-text index that already exists, you can use the Find command to find the index name:
>db.posts.getindexes ()
Get the index name from the above command, the index name of this example is Post_text_text, execute the following command to delete the index:
>db.posts.dropindex ("Post_text_text")
MongoDB Full Text Search