从版本2.4开始,MongoDB开始支持文本索引以搜索字符串内容. 文本搜索使用词干技术在字符串字段中查找指定的单词,方法是删除 a,an,the,等句号.目前,MongoDB支持大约15语言.
最初,文本搜索是一项实验性功能,但从版本2.6开始,默认情况下启用配置.但是如果您使用的是以前版本的MongoDB,则必须使用以下代码启用文本搜索 :
>db.adminCommand({setParameter:true,textSearchEnabled:true})
请考虑下的以下文档帖子包含帖子文本及其标签的集合 :
{ "post_text": "enjoy the mongodb articles on IT屋", "tags": [ "mongodb", "it1352" ] }
我们将在post_text字段上创建一个文本索引,以便我们可以在帖子中搜索文本 :
>db.posts.ensureIndex({post_text:"text"})
现在我们在post_text字段上创建了文本索引,我们将在文本中搜索所有包含 it1352字样的帖子.
>db.posts.find({$text:{$search:"it1352"}})
以上命令返回以下结果文件,其文字中包含 it1352字样 :
{ "_id" : ObjectId("53493d14d852429c10000002"), "post_text" : "enjoy the mongodb articles on it1352", "tags" : [ "mongodb", "it1352" ] } { "_id" : ObjectId("53493d1fd852429c10000003"), "post_text" : "writing tutorials on mongodb", "tags" : [ "mongodb", "tutorial" ] }
如果你使用旧版本的MongoDB,你必须使用以下命令 :
>db.posts.runCommand("text",{search:" it1352 "})
与普通搜索相比,使用文本搜索大大提高了搜索效率.
删除现有文字index,首先使用以下查询查找索引名称 :
>db.posts.getIndexes()
从上面的查询中获取索引的名称后,运行以下命令.这里, post_text_text 是索引的名称.
>db.posts.dropIndex("post_text_text")