蒙戈查询在阵列
问题描述:
文献例如蒙戈查询在阵列
{
"_id": 1,
"test": {
"item_obj": {
"item1": ["a", "b"],
"item2": ["c"],
"item3": ["a", "d"]
}
}
}
欲fetch documents where "a" exists in test.item_obj
的对象。 “a”可能存在于任何阵列中。我们不知道item_obj中存在的键(不知道item1,item2或item3是否存在)。
需要rails-mongo查询。
答
如果这是你的搜索情况,那么你看它的任何方式,你需要的条款的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" }
}
}
}
这基本上是同样的事情,但更长时间纠缠不清。但最终在原子更新中更容易处理。当然,查询文档中的值也完全一样。