我正在尝试跨多个字段查找搜索字符串中的所有单词。例如:
如果我要在此数据中搜索“java coffee”:
{ _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 Hut" },
{ _id: 6, name: "Java Coffee", description: "goods Hut" },
{ _id: 7, name: "Coffee Shop", description: "Just coffee Java" }
我希望它在每个字段中单独搜索每个词,并返回在任何指定字段中包含每个搜索词的所有文档。
由于这些匹配项,我应该返回 id 1、6 和 7 作为结果:
{ _id: 1, name: "**Java** Hut", description: "**Coffee** and cakes" },<br>
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },<br>
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },<br>
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },<br>
{ _id: 5, name: "Java Shopping", description: "Indonesian goods Hut" },<br>
{ _id: 6, name: "**Java Coffee**", description: "goods Hut" },<br>
{ _id: 7, name: "Coffee Shop", description: "Just **coffee Java**" }
关于如何以有效的方式让 Mongo 执行它,我有什么想法吗?
最佳答案
您可以添加 text
index添加到您的收藏中以启用对多个字段的文本搜索。在这种情况下:
db.test.createIndex({name: 'text', description: 'text'})
然后,要查找在任一字段中同时包含“java”和“coffee”的文档,您可以执行text search。查询同时引用这两个词以要求找到这两个词。引用这些词将它们变成 phrases它调用逻辑 AND 行为而不是 OR。
db.test.find({$text: {$search: '"java" "coffee"'}})
关于MongoDB - 在多个字段中查找所有搜索字符串单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39007184/