本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$text
该$text运算符用于对文档集合中的文本索引字段执行全文搜索。此运算符允许您搜索包含特定单词或短语的文档,并且可以与其他查询运算符结合使用以根据其他条件筛选结果。
参数
-
$search:要搜索的文本字符串。
示例(MongoDB 外壳)
以下示例演示如何使用$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" }
上面的命令返回的文档的文本索引字段包含任何形式的 “兴趣”,“star_rating” 等于 5。
代码示例
要查看使用该$text命令的代码示例,请选择要使用的语言的选项卡: