2017-10-04 93 views
1

我有一個內部包含產品(對象)的數組。它看起來像:我應該怎麼做一個聚合?

[ 
{_id: 123, name:'first', category:'Vape', property:[ 
    {key:'brand', values:'Eleaf'}, 
    {key:'mechmode', values:'some'}, 
    {key:'color', values:['red', 'blue']}, 
    {key:'batrtype', values:'some2'}, 
]}, 
{_id: 1234, name:'second', category:'Vape1', property:[ 
    {key:'brand', values:'Eleaf1'}, 
    {key:'mechmode', values:'some'}, 
    {key:'color', values:['black']}, 
    {key:'batrtype', values:'some2'} 
]}, 
{_id: 12345, name:'third', category:'Vape3', property:[ 
    {key:'brand', values:'Eleaf3'}, 
    {key:'mechmode', values:'some'}, 
    {key:'color', values:['green', 'yellow']}, 
    {key:'batrtype', values:'some2'} 
]}, 
{_id: 123456, name:'fourth', category:'Vape', property:[ 
    {key:'brand', values:'Eleaf'}, 
    {key:'mechmode', values:'some'}, 
    {key:'color', values:['red', 'green']}, 
    {key:'batrtype', values:'some2'} 
]} 
] 

從客戶

{category:'Vape', body:{brand:'Eleaf', color:'red'}} 

請求我應該怎麼做蒙戈合計獲得具有品牌=「Eleaf」 和顏色的產品=紅色根據要求?

有人可以幫忙嗎?

+0

該數組是作爲單個字段存儲在文檔中的,還是集合中的文檔列表? – Joe

+0

它是集合中的文檔列表 –

回答

0

我想這應該做的伎倆:

db.products.find({ 
    category: "Vape", 
    $and: [ 
     { property: { $elemMatch: { key: "brand", value: "Eleaf1" }, 
     { property: { $elemMatch: { key: "color", value: "red" } 
    ]}) 

我不知道你的數據的結構是最好的做法。如果它們被稱爲「品牌」的字段的值爲「顏色」而不是鍵/值對,則可能會更容易一些。

1

bgraham如果您使用的是find,則答案正確。要做到同樣的事情在一個聚合管道,使用$match,如:

db.aggregate([{$match:{ 
    category: "Vape", 
    $and: [ 
    { property: { $elemMatch: { key: "brand", value: "Eleaf" }, 
    { property: { $elemMatch: { key: "color", value: "red" } 
    ] 
}}]) 

然後,您可以添加到陣列中,你需要任何額外的流水線階段。

+0

謝謝,似乎它工作=) –