本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$text
$text 運算子用於對文件集合中的文字索引欄位執行全文搜尋。此運算子可讓您搜尋包含特定單字或片語的文件,並可與其他查詢運算子結合,根據其他條件篩選結果。
參數
-
$search:要搜尋的文字字串。
範例 (MongoDB Shell)
下列範例示範如何使用 $text運算子來搜尋包含「興趣」一詞的文件,並根據「star_rating」欄位篩選結果。
建立範例文件
db.test.insertMany([ { "_id": 1, "star_rating": 4, "comments": "apple is red" }, { "_id": 2, "star_rating": 5, "comments": "pie is delicious" }, { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" }, { "_id": 4, "star_rating": 2, "comments": "bake the apple pie in the oven" }, { "_id": 5, "star_rating": 5, "comments": "interesting couch" }, { "_id": 6, "star_rating": 5, "comments": "interested in couch for sale, year 2022" } ]);
建立文字索引
db.test.createIndex({ comments: "text" });
查詢範例
db.test.find({$and: [{star_rating: 5}, {$text: {$search: "interest"}}]})
輸出
{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" }
{ "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }
上述命令會傳回具有文字索引欄位的文件,其中包含任何形式的「興趣」和等於 5 的「star_rating」。
程式碼範例
若要檢視使用 $text命令的程式碼範例,請選擇您要使用的語言標籤: