我遵循教程说明:https://docs.mongodb.com/manual/core/index-text/
这是示例数据:
db.stores.insert(
[
{ _id: 1, name: "Java Hut", description: "Coffee and cakes" },
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
{ _id: 5, name: "Java Shopping", description: "Indonesian goods" }
]
)案例1:db.stores.find( { $text: { $search: "java coffee shop" } } ) => FOUND
案例2:db.stores.find( { $text: { $search: "java" } } ) => FOUND
案例3:db.stores.find( { $text: { $search: "coff" } } ) => NOT
我预计案例3是FOUND,因为查询与java coffee shop的一部分匹配
发布于 2021-03-30 07:52:45
案例3将不适用于$text操作符,原因是Mongo如何创建文本索引。
Mongo采用文本索引字段值,并为字符串中的每个惟一单词创建单独的索引,而不是为字符(!)创建索引。
这意味着,在你的例子中,对于一个对象:
字段名将有两个索引:
字段描述将有3个索引:
$text操作符将$search值与这些索引进行比较,这就是为什么"coff“不能工作的原因。
如果您强烈希望利用索引的优势,就必须使用$text操作符,但它并不能提供所有的灵活性,就像您想要的那样。
溶液
您可以简单地使用带有case敏感性选项(i)的$regex,并通过跳过和限制优化查询。
如果您希望返回所有文档,并且集合很大,则$regex将导致性能问题。
您也可以检查本文的https://medium.com/coding-in-depth/full-text-search-part-1-how-to-create-mongodb-full-and-partial-text-search-c09c0bae17a3,并可能为此使用通配符索引,但我不知道这是否是一个好的实践。
https://stackoverflow.com/questions/66865798
复制相似问题