Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB full-text search


May 17, 2021 MongoDB


Table of contents


MongoDB full-text search

Full-text retrieval establishes an index of each word, indicating the number and location of times the word appears in the article, and when the user queries, the search program looks for it according to a pre-established index and feedbacks the results of the search back to the user's retrieval method.

This process is similar to the process of looking through a dictionary's retrieval table.

MongoDB supports full-text retrieval starting with version 2.4 and currently supports full-text indexing in 15 languages (Chinese for the time being).

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

Enable full-text retrieval

MongoDB turns full-text retrieval on by default after version 2.6, and if you use the previous version, you'll need to use the following code to enable full-text retrieval:

>db.adminCommand({setParameter:true,textSearchEnabled:true})

Or use the command:

mongod --setParameter textSearchEnabled=true

Create a full-text index

Consider the document data for the following posts collection, which contains the content of post_text articles and tags:

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

We can index post_text full text of the field so that we can search for content in the article:

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

Use full-text indexes

Now that we've post_text full-text index of the content, we can search for keywords in w3cschool.cn:

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

The following command returns document data w3cschool.cn key words as follows:

{ 
   "_id" : ObjectId("53493d14d852429c10000002"), 
   "post_text" : "enjoy the mongodb articles on w3cschool.cn", 
   "tags" : [ "mongodb", "w3cschool" ]
}
{
   "_id" : ObjectId("53493d1fd852429c10000003"), 
   "post_text" : "writing tutorials on w3cschool.cn",
   "tags" : [ "mongodb", "tutorial" ] 
}

If you're using an older version of MongoDB, you can use the following commands:

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

Using full-text indexing can improve search efficiency.


Delete the full-text index

To delete a full-text index that already exists, you can use the find command to find the index name:

>db.posts.getIndexes()

The index name is obtained from the above command, and in this case the index name post_text_text, the following command is executed to remove the index:

>db.posts.dropIndex("post_text_text")