2015-09-16 133 views
3
我有在得到这个结果的难度

检索值:Meteor.js +的MongoDB ::从深度嵌套阵列

{ 
    "_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:aggregate,但无法使其工作,因为我没有找到一个新手友好的文档。

您的解决方案和友好的解释非常感谢!

回答

0

在这里使用聚合看起来像是矫枉过正。下面是一个例子函数提取出口姓名(或名称):

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'); 
+0

这是一个非常紧凑的解决方案,而不是我试图过滤数据的方法。谢谢! – kyooriouskoala

0

很确定没有办法用标准流星来做到这一点。聚合包可能有帮助,但我还没有使用它。我会使用方法1来检索文档,然后过滤文档以使用标准javascript查找您想要的信息(或类似下划线可能会帮助您。)

+0

感谢您的提示! – kyooriouskoala