【发布时间】:2016-06-13 06:30:38
【问题描述】:
我有一大堆这样的文件:
{
_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,所以我不确定最好的方法。
【问题讨论】:
标签: mongodb aggregation-framework