我的文档巨大的一堆这样:蒙戈总结:总和计数数组重复值田间
{
_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