English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Text Search

From2.4Starting from the version, MongoDB begins to support text indexing to search for string content. Text Search (text search) uses stemming analysis technology to find specific words in string fields by removing stemming analysis stop words (such as a, an, The, etc.). Currently, MongoDB supports approximately15language.]}

Enable text search

Initially, "Text Search (Text Search)" was an experimental feature, but from2.6version started, this configuration is enabled by default.

Create text index

Consider the followingpostsDocuments in the collection containing the post text and its tags-

> db.posts.insert({
   "post_text": "enjoy the mongodb articles on w3codebox",
   "tags": ["mongodb", "w3codebox"]
}
{
	"post_text": "writing tutorials on mongodb"
	"tags": ["mongodb", "tutorial"]
})
WriteResult({ "nInserted": 1 })

We will create a text index on the post_text field so that we can search within the text of the posts-

>db.posts.createIndex({post_text:"text"})
{
	"createdCollectionAutomatically": true,
	"numIndexesBefore": 1,
	"numIndexesAfter": 2,
	"ok": 1
}

Using text index

Now, we have created a text index on the post_text field, and we will searchw3codeboxAll posts containing the word in the text.

> db.posts.find({$text:{$search:"w3codebox"}}).pretty(){
	"_id": ObjectId("5dd7ce28f1dd4583e7103fe0")
	"post_text": "enjoy the mongodb articles on w3codebox",
	"tags": [
		"mongodb",
		"w3codebox"
	]
}

The above command returns the following result document, whichw3codeboxThe published text contains the word:

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

Delete text index

To delete the existing text index, please first use the following query to find the name of the index-

>db.posts.getIndexes()[
	{
		"v" : 2,
		"key" : {
			"_id": 1
		},
		"name": "_id_",
		"ns" : "mydb.posts"
	},
	{
		"v" : 2,
		"key" : {
			"fts" : "text",
			"ftsx" : 1
		},
		"name" : "post_text_text",
		"ns" : "mydb.posts",
		"weights" : {
			"post_text" : 1
		},
		"default_language" : "english",
		"language_override" : "language",
		"textIndexVersion" : 3
	}
]
>

After obtaining the index name from the above query, run the following command. Here,post_text_textIs the name of the index.

>db.posts.dropIndex("post_text_text")
{ "nIndexesWas" : 2, "ok" : 1 }