2011-11-16 104 views
66

如果我有這樣的記錄;通過多個數組項搜索mongodb

{ 
    "text": "text goes here", 
    "words": ["text", "goes", "here"] 
} 

我怎樣才能匹配來自它在MongoDB中多個單詞?當匹配一個單詞我可以做到這一點;

db.find({ words: "text" }) 

但是,當我嘗試這個多個單詞,它不工作;

db.find({ words: ["text", "here"] }) 

我猜測,通過使用數組,它會嘗試將整個數組與匹配記錄中的數組進行匹配,而不是匹配單個內容。

回答

112

取決於是否你想查找文檔,其中包含words兩種元素(texthere)使用$all

db.things.find({ words: { $all: ["text", "here"] }}); 

或其中之一(texthere)使用$in

db.things.find({ words: { $in: ["text", "here"] }}); 
+3

$都是我在找的,謝謝。 :) –

+3

這也幫了我,我需要它找到一個數組中的對象ID,以及像$ in:[ObjectId(「4f9f2c336b810d0cf0000017」)]失敗,$ in:[「4f9f2c336b810d0cf0000017」]工作 – jbnunn

+0

你也可以在mangodb支持頁面找到另一種方法來執行此操作http://docs.mongodb.org/manual/core/indexes/#indexes-on-sub-documents和http://docs.mongodb.org/manual/core/indexes /#多鍵的索引 –