【发布时间】:2017-06-07 01:23:04
【问题描述】:
下面是我的mongodb结构:
[{
_id: '111',
items: [{
productId: '123'
}]
}, {
_id: '222',
items: [{
productId: '123'
}, {
productId: '456'
}]
}, {
_id: '333',
items: [{
productId: '123'
}, {
productId: '456'
}, {
productId: '789'
}]
}]
我希望对productId 进行分组和计数,结果是:
[{
productId: '123',
count: 3
}, {
productId: '456',
count: 2
}, {
productId: '789',
count: 1
}]
好吧,我试过像这样使用aggregation,但我想我弄错了:
const aggregatorOpts = [{
$group: {
_id: "$items.productId",
count: { $sum: 1 }
}
}]
Model.aggregate(aggregatorOpts).exec()
我明白了:
result [
{ _id: [ '123' ], count: 1 },
{ _id: [ '123', '456' ], count: 1 },
{ _id: [ '123', '456', '789' ], count: 1 }
]
任何有关如何进行聚合的帮助可能都会受到赞赏,请不要假设模型有任何变化。
提前致谢!
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework