[英]Meteor.js + MongoDB :: Retrieve values from deeply nested arrays
我很难得到这个结果:
["Chadstone", "South Yarra"]
当给出这两个值时:
name: 'Soda Rock'
city: 'Melbourne'
从这份文件:
{
"_id" : "axHqB4NjXbWwphik3",
"name" : "Soda Rock",
"storeLocation" : [
{
"state" : "Victoria",
"outlet" : [
{
"city" : "Melbourne",
"name" : ["Chadstone", "South Yarra"]
},
{
"city" : "Geelong",
"name" : ["Myer", "Market Square"]
}
]
},
{
"state" : "New South Wales",
"outlet" : [
{
"city" : "Sydney",
"name" : ["Westfield", "Broadway Shopping Centre"]
}
]
}
]
}
我尝试了一些方法,但没有输出我想要的结果。
方法#1:
Stores.find(
{
'name': 'Soda Rock',
'storeLocation.outlet.city': 'Melbourne'
},
{
_id: 0,
'storeLocation.outlet.name.$': 1
}
);
结果:
{
"storeLocation" : [
{
"state" : "Victoria",
"outlet" : [
{
"city" : "Melbourne",
"name" : ["Chadstone", "South Yarra"]
},
{
"city" : "Geelong",
"name" : ["Myer", "Market Square"]
}
]
}
]
}
方法#2:
Stores.find(
{
'name': 'Soda Rock',
'storeLocation.outlet.city': {
'Melbourne'
}
},
{
_id: 0,
'storeLocation.outlet.name': 1
}
);
结果:
{
"storeLocation" : [
{
"outlet" : [
{
"name" : ["Chadstone", "South Yarra"]
},
{
"name" : ["Myer", "Market Square"]
}
]
},
{
"outlet" : [
{
"name" : ["Westfield", "Broadway Shopping Centre"]
}
]
}
]
}
我也试过使用meteorhacks:聚合但无法使它工作,因为我还没有找到一个新手友好的文档。
非常感谢您的解决方案和友好的解释!
很确定没有办法用标准Meteor做到这一点。 聚合包可能会有所帮助,但我也没有使用它。 我使用方法1来检索文档,然后过滤文档以使用标准javascript找到所需的信息(或类似下划线的内容可能会帮助你。)
在这里使用聚合似乎有点矫枉过正。 这是一个提取插座名称的示例函数:
var findOutletName = function(name, city) {
var doc = Stores.findOne({name: name});
var outletName = null;
_.each(doc.storeLocation, function(location) {
_.each(location.outlet, function(outlet) {
if (outlet.city === city)
outletName = outlet.name;
});
});
return outletName;
};
您可以这样使用:
findOutletName('Soda Rock', 'Melbourne');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.