MongoDB tutorials
9. Text search – MongoDB tutorials
Video tutorial:
Till now we have searched based on field values, less than, greater than, $and and $or operators. Sometimes you want a substring to be searched inside a string. For that, first, you have to add an index on that field. For example, I want to search “best” inside the “content” field of posts collection:
db.posts.ensureIndex({ "content": "text" })
“text” is a name that will be used during the search. Now to search substring, we have to use this text as an operator succeeding by $ sign:
db.posts.find({ $text: { $search: "best" } })
You see the $text is the same as the value in ensureIndex function. Now in order to drop an index from MongoDB collection, you have to call a function named dropIndex() and pass it the parameter such that it has the field name, underscore and then the name of the index:
db.posts.dropIndex("content_text")
Here “content” is the name of field in posts collection, then an underscore, then the name of index we created which was “text”.