>db.adminCommand({setParameter:true, textSearchEnabled:true})
或者使用命令:mongod --setParameter textSearchEnabled=true
> db.posts.insert([ ... { ... "post_text": "enjoy the mongodb articles on bianchengbang", ... "tags": ["mongodb", "bianchengbang"] ... }, ... { ... "post_text" : "writing tutorials on mongodb", ... "tags" : [ "mongodb", "tutorial" ] ... } ... ]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })若要在 post_text 字段上创建全文索引,以便我们可以直接搜索字段中的内容,可以像下面这样:
> db.posts.createIndex({post_text:"text"}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.posts.find({$text:{$search:"bianchengbang"}}).pretty() { "_id" : ObjectId("6041dfc3835e4aa734b591df"), "post_text" : "enjoy the mongodb articles on bianchengbang", "tags" : [ "mongodb", "bianchengbang" ] }如果您使用的是旧版本的 MongoDB,则可以使用以下命令:
>db.posts.runCommand("text",{search:"bianchengbang"})
> db.posts.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "bianchengbang.posts" }, { "v" : 2, "key" : { "_fts" : "text", "_ftsx" : 1 }, "name" : "post_text_text", "ns" : "bianchengbang.posts", "weights" : { "post_text" : 1 }, "default_language" : "english", "language_override" : "language", "textIndexVersion" : 3 } ]通过运行结果可以看出,我们前面创建的索引的名称为“post_text_text”,接下来就可以使用 dropIndex() 方法来删除指定的索引了,如下所示:
> db.posts.dropIndex("post_text_text") { "nIndexesWas" : 2, "ok" : 1 }
本文链接:http://task.lmcjl.com/news/17702.html