MongoDB full text search
Full-text search creates an index for each word, indicating the number and location of the word in the article. When the user queries, the search program searches based on the pre-established index and will search The results are fed back to the user's search method.
This process is similar to the process of looking up words through the search word list in the dictionary.
MongoDB supports full-text search starting from version 2.4, and currently supports full-text indexing in 15 languages (Chinese is not supported for the time being).
danish
dutch
- ##english
- finnish ##french
- german
- hungarian
- italian
- norwegian
- portuguese
- romanian
- russian
- spanish
- swedish
- turkish
MongoDB enables full-text search by default after version 2.6. If you use the previous version, you need to use the following code to enable full-text search:
>db.adminCommand({setParameter:true,textSearchEnabled:true})
Or use the command:
mongod --setParameter textSearchEnabled=trueCreate a full-text index
Consider the document data of the following posts collection, including article content (post_text) and tags (tags):
{ "post_text": "enjoy the mongodb articles on w3cschool.cc", "tags": [ "mongodb", "w3cschool" ] }
We can establish a full-text index on the post_text field so that we can search the content within the article:
>db.posts.ensureIndex({post_text:"text"})Use full-text index
Now we have established a full-text index on the post_text field Full-text index, we can search for the keyword w3cschool.cc in the article:
>db.posts.find({$text:{$search:"w3cschool.cc"}})
The following command returns the following document data containing the w3cschool.cc keyword:
{ "_id" : ObjectId("53493d14d852429c10000002"), "post_text" : "enjoy the mongodb articles on w3cschool.cc", "tags" : [ "mongodb", "w3cschool" ] } { "_id" : ObjectId("53493d1fd852429c10000003"), "post_text" : "writing tutorials on w3cschool.cc", "tags" : [ "mongodb", "tutorial" ] }
If you are using the old version of MongoDB, you can use the following command:
>db.posts.runCommand("text",{search:" w3cschool.cc"})
Using full-text index can improve search efficiency.
Delete full-text indexTo delete an existing full-text index, you can use the find command to find the index name:
>db.posts.getIndexes()
Get the index name through the above command, in this example The index name is post_text_text. Execute the following command to delete the index:
>db.posts.dropIndex("post_text_text")