Latest web development tutorials

MongoDB full-text search

The establishment of a full-text search index for each word, indicating the number and location of the word appears in the article, when a user's query, the search program will be established in advance to find the index, and the search results back to the user's search method.

This process is similar to the search word by word dictionary table retrieval process.

MongoDB version 2.4 from the start to support full-text search, currently supports 15 languages ​​(temporarily does not support Chinese) full-text index.

  • danish
  • dutch
  • english
  • finnish
  • french
  • german
  • hungarian
  • italian
  • norwegian
  • portuguese
  • romanian
  • russian
  • spanish
  • swedish
  • turkish

Enable full-text search

After MongoDB version 2.6 is enabled by default full-text search, 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=true

Create a full-text index

Consider the following posts document data sets, including the content of the article (post_text) and labels (tags):

{
   "post_text": "enjoy the mongodb articles on w3cschool.cc",
   "tags": [
      "mongodb",
      "w3cschool"
   ]
}

We can build full-text index of post_text field, so we can search the content of the article:

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

Use full-text indexing

Now that we have established a full-text index of post_text, we can search for key words in the article w3cschool.cc:

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

The following command returns the document data contained w3cschool.cc following keywords:

{ 
   "_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 an older version of MongoDB, you can use the following command:

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

Use full-text indexing can improve search efficiency.


Remove full-text indexing

Delete the existing full-text index, you can use the find command to find the index name:

>db.posts.getIndexes()

Get the name of the index above command, in this case the index named post_text_text, execute the following command to delete the index:

>db.posts.dropIndex("post_text_text")