MongoDB Full-Text Search

Full-text search builds an index for each word, indicating the number of times and positions in which the word appears in the article. When a user queries, the retrieval program searches based on the pre-built index, and feeds the search results back to the user.

This process is similar to looking up a word through the index of a dictionary.

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

Enable Full-Text Search

MongoDB has full-text search enabled 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 Full-Text Index

Consider the following document data in the posts collection, which contains article content (post_text) and tags:

{
   "post_text": "enjoy the mongodb articles on Example",
   "tags": [
      "mongodb",
      "example"
   ]
}

We can create a full-text index on the post_text field, so that we can search the content within the articles:

>db.posts.ensureIndex({post_text:"text"})

Use Full-Text Index

Now that we have created a full-text index on post_text, we can search for the keyword example in the articles:

>db.posts.find({$text:{$search:"example"}})

The following command returns the document data containing the keyword example:

{ 
   "_id" : ObjectId("53493d14d852429c10000002"), 
   "post_text" : "enjoy the mongodb articles on Example", 
   "tags" : [ "mongodb", "example" ]
}

If you are using an older version of MongoDB, you can use the following command:

>db.posts.runCommand("text",{search:"example"})

Using full-text indexes can improve search efficiency.


Delete Full-Text Index

To 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")
Other Extensions