在 MongoDB 中為文字搜尋建立索引
讓我們建立一個帶文件的集合 -
> db.demo331.insertOne({"Words":"This is a MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e521c35f8647eb59e562089") } > db.demo331.insertOne({"Words":"THIS is a MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e521c36f8647eb59e56208a") }
在集合中使用 find() 方法顯示所有文件 -
> db.demo331.find();
這將產生以下輸出 -
{ "_id" : ObjectId("5e521c35f8647eb59e562089"), "Words" : "This is a MySQL" } { "_id" : ObjectId("5e521c36f8647eb59e56208a"), "Words" : "THIS is a MongoDB" }
以下是為文字搜尋建立索引的查詢 -
> db.demo331.createIndex( {Words: "text" } ); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo331.find({$text:{$search:"MySQL"}});
這將產生以下輸出 -
{ "_id" : ObjectId("5e521c35f8647eb59e562089"), "Words" : "This is a MySQL" }
廣告