我的文檔巨大的一堆這樣:蒙戈總結:總和計數數組重複值田間
{
_id: '1',
colors: [
{ value: 'red', count: 2 },
{ value: 'blue', count: 3}
]
shapes: [
{ value: 'cube', type: '3d' },
{ value: 'square', type: '2d'}
]
},
{
_id: '2',
colors: [
{ value: 'red', count: 7 },
{ value: 'blue', count: 34},
{ value: 'yellow', count: 12}
]
shapes: [
{ value: 'prism', type: '3d' },
{ value: 'triangle', type: '2d'}
]
}
通過使用$unwind
和$addToSet
,因爲這樣的:
db.getCollection('coll').aggregate([{$unwind:"$colors"},{$unwind:"$shapes"},{$group:{_id:null,colors:{$addToSet:"$colors"},shapes:{$addToSet:"$shapes"}])
我能得到如下:
{
"_id" : null,
"colors" : [
{ "value" : "red", "count" : 2 },
{ "value" : "blue", "count" : 3 },
{ "value" : "red", "count" : 7 },
{ "value" : "blue", "count" : 34 },
{ "value" : "yellow", "count" : 12 }
]
"shapes" : [
{ value: 'cube', type: '3d' },
{ value: 'square', type: '2d'}
{ value: 'prism', type: '3d' },
{ value: 'triangle', type: '2d'}
]
}
然而我想要的是判斷重複的唯一的領域「值」,並總結「計數」字段重複,即
{
"_id" : null,
"colors" : [
{ "value" : "red", "count" : 9 },
{ "value" : "blue", "count" : 37 },
{ "value" : "yellow", "count" : 12 }
]
"shapes" : [
{ value: 'cube', type: '3d' },
{ value: 'square', type: '2d'}
{ value: 'prism', type: '3d' },
{ value: 'triangle', type: '2d'}
]
}
這question表明我可以使用$colors.value
作爲_id
字段和$sum
與總的count
。然而,因爲我有第二個數組$unwind
和聚合/ $group
,我不確定最好的方式去做這件事。
這看起來不錯。讓我試試看!我也編輯了我的帖子,以刪除錯誤的撇號-_-錯字嘉豪!非常感謝! :) @chridam – Tacocat
呃,你能向我解釋這是什麼嗎?:'「shapes」:{「$ first」:「$ shapes」}'我可能在誤解之下運作..:3 – Tacocat
@Tacocat增加了一些解釋,希望你能理解它在管道中的使用。在這裏它使用了更多的機制來獲取前一個管道中的'shapes'字段到分組中,而不影響當前的聚合。 – chridam