2014-09-21 35 views
0

我有我試圖文本索引文件是文件列表的問題:MongoDB的文本索引對象數組列

我先插入到DB:

db.userlikes.insert({ 
    "data": [ 
    { 
     "category": "Non-profit organization", 
     "name": "Animals" 
    }, 
    { 
     "category": "Community", 
     "name": "Computers" 
    } 
    ] 
}) 

然後我想以創建類別列的索引:

db.userlikes.ensureIndex({"data.category": "text"}) 

但是,當我試圖尋找我沒有得到任何結果:

db.userlikes.find({"data.category": "profit"}) 

是不是可以索引這種方式?最好的方法是將每個文檔分別插入到數組中(「數據」)?這將是一個開銷,因爲我只想插入到從API獲取的數據庫響應中。

請幫幫我。

謝謝

回答

1

請閱讀the documentation concerning text searches

文本搜索的工作原理是這樣

db.userlikes.find({ $text: {$search:"profit"} }) 

,因爲只能有每收集一個文本索引(儘管多個字段可以被索引)。

+0

,您好:感謝您的回覆,我也試過db.userlikes.find({$文字:{$搜索:「利潤」}}),但沒有運氣:(我仍然沒有結果 – EA9 2014-09-21 12:46:04

+0

然後你我創建了一個包含示例數據的集合,通過db.userlikes.ensureIndex({「data.category」:「text」})添加了一個文本索引,併發送了查詢db.userlikes.find( {$ text:{$ search:「profit」}})',這給了我預期的結果。 – 2014-09-22 10:54:58

0

我嘗試了相同的步驟EA9。它似乎爲我工作。您可能想檢查是否有拼寫錯誤。這是我的輸出與命令。

db.userlikes.insert({ 
... "data": [ 
...  { 
...  "category": "Non-profit organization", 
...  "name": "Animals" 
...  }, 
...  { 
...  "category": "Community", 
...  "name": "Computers" 
...  } 
... ] 
... }); 
WriteResult({ "nInserted" : 1 }) 

db.userlikes.find(); 

{ "_id" : ObjectId("541ff8dc1dca72499395cbcf"), "data" : [ { "category" : "Non-profit organization", "name" : "Animals" }, { "category" : "Community", "name" : "Computers" } ] } 


db.userlikes.ensureIndex({"data.category": "text"}) 


{ 
    "createdCollectionAutomatically" : false, 
    "numIndexesBefore" : 1, 
    "numIndexesAfter" : 2, 
    "ok" : 1 
} 


db.userlikes.find({ $text: { $search: "profit" } }); 


{ "_id" : ObjectId("541ff8dc1dca72499395cbcf"), "data" : [ { "category" : "Non-profit organization", "name" : "Animals" }, { "category" : "Community", "name" : "Computers" } ] }