Home >>MongoDB Tutorial >MongoDB Text Search
Beginning with version 2.4, MongoDB started supporting text indexes to search for content within string. Text Search uses stemming techniques by dropping stemming stop terms such as a, an the, etc to look for specified words in the string fields. MongoDB officially supports about 15 languages.
Text Search was initially an experimental feature, but the configuration is allowed by default, beginning with version 2.6.
Find the following post collection document containing the post text and its tags.
> db.posts.insert({ "post_text": "enjoy the mongodb articles on phptpoint", "tags": ["mongodb", "phptpoint"] } { "post_text" : "writing tutorials on mongodb", "tags" : [ "mongodb", "tutorial" ] }) WriteResult({ "nInserted" : 1 })
On the post_text field, we will create a text index so we can search within the text of our posts.
>db.posts.createIndex({post_text:"text"}) { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
We'll search for all posts with the word phptpoint in their text now that we've built the text index on the post_text field.
> db.posts.find({$text:{$search:"phptpoint"}}).pretty() { "_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"), "post_text" : "enjoy the mongodb articles on phptpoint", "tags" : [ "mongodb", "phptpoint" ] }
The above command returned the following results documents in their post text with the word phptpoint.
{ "_id" : ObjectId("53493d14d852429c10000002"), "post_text" : "enjoy the mongodb articles on phptpoint", "tags" : [ "mongodb", "phptpoint" ] }
To delete an existing text index, first find the index name using the query below –
>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 } ] >
Run the following command after obtaining the name of your index from the above query. Here the index name is post_text_text.
>db.posts.dropIndex("post_text_text") { "nIndexesWas" : 2, "ok" : 1 }