2016-12-27 60 views
0

有沒有任何方法可以在沒有根文檔的情況下從集合的字段(數組)中選擇所有嵌入式文檔?例如,給定這個集合MongoDB按照無標準條件選擇所有嵌入式文檔

{ "_id" : 1, "cars" : [{"brand": "audi", "color": "red"}, {"brand": "audi", "color": "yellow"}]} 
{ "_id" : 2, "cars" : [{"brand": "audi", "color": "blue"}, {"brand": "seat"}]} 

我想與下面的輸出選擇所有汽車品牌audi

{"brand": "audi", "color": "red"} 
{"brand": "audi", "color": "blue"} 
{"brand": "audi", "color": "yellow"} 

這似乎並不可能只db.collection.find()projection,因爲它的匹配標準始終與根文檔相關。

+0

@SagarReddy這將選擇至少有一輛汽車匹配brand ='audi'的所有根對象。但是例如,第二份文件中的「座位」車輛將被錯誤地包括在內。 –

+0

'db.collection.find({'cars.brand':'audi'},{'cars。$':1})' – styvane

+0

@Styvane這將只會得到第一個匹配記錄。我認爲OP需要所有匹配的條目。 – Veeram

回答

-1

您可以使用聚合將:

  • $unwind你車陣
  • $match只有奧迪brand
  • $group按品牌&顏色來刪除重複
  • $project重組輸出

查詢:

db.cars.aggregate([{ 
    $unwind: '$cars' 
}, { 
    $match: { 
     'cars.brand': 'audi' 
    } 
}, { 
    $group: { 
     '_id': { 'brand': '$cars.brand', 'color': '$cars.color' } 
    } 
}, { 
    $project: { 
     _id: 0, 
     'brand': '$_id.brand', 
     'color': '$_id.color' 
    } 
}]) 
+0

您是否可以將嵌套文檔嵌套$ unwind? –

+0

您可以在根目錄之後展開嵌套數組:'db.cars.aggregate([{$ unwind:'$ topArray'},{$ unwind:'$ topArray.cars'}])' –

0

隨着蒙戈3.4版本,你可以使用$replaceRoot操作來實現你所追求的。

db.cars.aggregate([{ 
    $unwind: "$cars" 
}, { 
    $match: { 
     "cars.brand": "audi" 
    } 
}, { 
    $replaceRoot: { 
     newRoot: "$cars" 
    } 
}]) 
相關問題