2016-08-17 199 views
3

我试图在跨多个字段的搜索字符串中查找所有单词。例如:MongoDB - 在多个字段中查找所有搜索字符串单词

如果我在这个数据来搜索“的Java咖啡”:

{ _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**" } 

我如何能以高效的方式为蒙戈来执行它实现这一目标的任何想法?

回答

2

您可以将text index添加到您的收藏夹以启用多个字段的文本搜索。在这种情况下:

db.test.createIndex({name: 'text', description: 'text'}) 

然后,发现在任一场包含了“Java”和“咖啡”的文档,你可以执行text search查询与报价,要求这两个词来找到这两个词。引用这些词将它们变成phrases,它调用逻辑AND行为而不是OR。

db.test.find({$text: {$search: '"java" "coffee"'}}) 
+0

谢谢,这对我有效。如果其中一个单词是部分的,它甚至可以工作,如'jav'而不是'java'。你知道是否有办法让它适用于多个部分词汇? – Kendall

+0

我不希望部分单词在文本搜索中可靠地工作,因为它使用单词词干而不是部分匹配。 – JohnnyHK

0

如果搜索字符串是空格分隔的字符串,$ text操作符对每个术语执行逻辑OR搜索并返回包含任何术语的文档。

db.collection.find({ $text: { $search: "java coffee" } }) 

该查询将返回咖啡或java存在于该集合的任何文档中。

有关详细信息,请参阅manual

相关问题