MongoDB Full-Text Search
Full-text search creates an index for each word, indicating the number of times and the location where the word appears in the article. When a user queries, the retrieval program searches according to the pre-established index and feeds the results back to the user.
This process is similar to looking up characters through the index table in a dictionary.
MongoDB has supported full-text search since version 2.4 and currently supports full-text indexes in 15 languages.
- danish
- dutch
- english
- finnish
- french
- german
- hungarian
- italian
- norwegian
- portuguese
- romanian
- russian
- spanish
- swedish
- turkish
Enable full-text search
MongoDB enables full-text search by default after version 2.6. If you use an earlier 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=true
Create a full-text index
Consider the following document data of the posts collection, which contains article content (post_text) and tags:
{
"post_text": "enjoy the mongodb articles on Runoob",
"tags": [
"mongodb",
"runoob"
]
}
We can create a full-text index on the post_text field, so that we can search the content within articles:
>db.posts.ensureIndex({post_text:"text"})
Using a full-text index
Now that we have created a full-text index on post_text, we can search for the keyword runoob in articles:
>db.posts.find({$text:{$search:"runoob"}})
The following command returns the following document data containing the keyword runoob:
{
"_id" : ObjectId("53493d14d852429c10000002"),
"post_text" : "enjoy the mongodb articles on Runoob",
"tags" : [ "mongodb", "runoob" ]
}
If you are using an older version of MongoDB, you can use the following command:
>db.posts.runCommand("text",{search:"runoob"})
Using a full-text index can improve search efficiency.
Delete a full-text index
To delete an existing full-text index, you can use the find command to find the index name:
>db.posts.getIndexes()
Obtain 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")