2011-11-16 108 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 /#多键的索引 –