如果這是你的搜索情況,那麼你看它的任何方式,你需要的條款的JavaScript的評估,以解決當前的結構。在shell爲例(因爲你總有需要用到的JavaScript表達式):
db.collection.find(function() {
var root = this.test.item_obj;
return Object.keys(root).some(function(key) {
return root[key] == "a";
});
})
或爲mongoid是這樣的:
func = <<-eof
var root = this.test.item_obj;
return Object.keys(root).some(function(key) {
return root[key] == "a";
});
eof
Model.for_js(func)
但是,如果簡單地改變你的結構來定義「items_objects 「作爲一個數組如下:
{
"_id": 1,
"test": {
"item_objects": [
{ "name": "item1", "data": ["a","b"] },
{ "name": "item2", "data": ["c"] },
{ "name": "item3", "data": ["a","d"] }
}
}
}
然後找你想要的這裏是基本的:
db.collection.find({
"test.item_objects.data": "a"
})
或爲mongoid:
Model.where("test.item_objects.data" => "a")
嵌套數組是不是一個真正的偉大的想法了,所以也許生活:
{
"_id": 1,
"test": {
"item_objects": [
{ "name": "item1", "data": "a" },
{ "name": "item1", "data": "b" },
{ "name": "item2", "data": "c" },
{ "name": "item3", "data": "a" },
{ "name": "item3", "data": "d" }
}
}
}
這基本上是同樣的事情,但更長時間糾纏不清。但最終在原子更新中更容易處理。當然,查詢文檔中的值也完全一樣。