2015-06-30 292 views
0

首先,讓我說這個問題與mongo中有關嵌套數組的其他人稍有不同。通過對象的嵌套數組過濾數組元素

大多數人問如何獲得嵌套數組中的特定元素。我想獲得一個數組的所有元素,這個數組本身包含另一個包含給定值的數組。

我有文件,看起來像這樣的:

{ 
    _id: something, 
    value: something, 
    items: [{ 
     name: someItem, 
     price: somePrice, 
     stores:[ 
      {name: storeName, url: someUrl }, 
      {name: anotherStoreName, url: someOtherUrl} 
     ] 
    }, 
    { 
     name: someOtherItem, 
     price: someOtherPrice, 
     stores:[ 
      {name: storeName, url: someUrl }, 
      {name: yetAnotherStoreName, url: someOtherUrl} 
     ] 
    }] 
} 

我想是讓只擁有門店陣列中的給定存儲的項目元素。 這是,如果我問storeName,我應該在這個例子中得到兩個項目。但如果我要求anotherStoreName,我應該只獲取數組項的第一個元素。

搜索類似的問題並嘗試解決方案我只能得到第一個項目的匹配元素,但我想要所有的匹配元素。

我很感激任何幫助。

+0

您能告訴我們預期的結果嗎? – styvane

回答

0

您應該使用聚合框架來展開items數組上的元素,然後將它們視爲單個文檔。

db.data.aggregate([ 
    { 
     $unwind: "$items" 
    }, 
    { 
     $project: { 
      _id: 0, 
      items: "$items" 
     } 
    }, 
    { 
     $match: { 
      "items.stores.name": "yetAnotherStoreName" 
     } 
    } 
]); 
  • $項目只是讓你與文檔的重要組成部分的工作。
  • 這在使用你的驅動程序時要小心使用mongoshell。

結果。

Result image

0

您應該使用mongo aggregation獲得導致下面的方式。

首先使用$unwind分隔items的數組,然後添加匹配條件。

db.collection.aggregate([{ 
    $unwind: "$items" 
}, { 
    $match: { 
    "items.stores.name": "storeName" 
    } 
}, { 
    $project: { 
    _id: 0, 
    items: "$items" //you can add multiple fields here 
    } 
}]);