Mongodb Text Search
# MongoDB Full-Text Search
Full-text search creates an index for each word, indicating the number of times and the position of the word in the article. When a user queries, the search program searches based on the pre-built index and returns the results to the user.
This process is similar to looking up a word in a dictionary using its index.
MongoDB has supported full-text search since version 2.4 and currently supports full-text indexes for 15 languages.
* danish
* dutch
* english
* finnish
* french
* german
* hungarian
* italian
* norwegian
* portuguese
* romanian
* russian
* spanish
* swedish
* turkish
* * *
## Enabling Full-Text Search
MongoDB has full-text search enabled by default since version 2.6. If you are using 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
* * *
## Creating a Full-Text Index
Consider the following document data in the `posts` collection, which contains article content (`post_text`) and tags (`tags`):
{ "post_text": "enjoy the mongodb articles on Tutorial", "tags": [ "mongodb", "tutorial" ]}
We can create a full-text index on the `post_text` field, allowing us to search within the article content:
>db.posts.ensureIndex({post_text:"text"})
* * *
## Using the Full-Text Index
Now that we have created a full-text index on `post_text`, we can search for the keyword "tutorial" in the articles:
>db.posts.find({$text:{$search:"tutorial"}})
The following command returns the document data containing the keyword "tutorial":
{ "_id" : ObjectId("53493d14d852429c10000002"), "post_text" : "enjoy the mongodb articles on Tutorial", "tags" : [ "mongodb", "tutorial" ]}
If you are using an older version of MongoDB, you can use the following command:
>db.posts.runCommand("text",{search:"tutorial"})
Using a full-text index can improve search efficiency.
* * *
## Deleting a Full-Text Index
To delete an existing full-text index, you can use the `find` command to look up the index name:
>db.posts.getIndexes()
After obtaining the index name with 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")
YouTip