2016-08-17 196 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

相關問題