本文介绍了猫鼬组和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的mongodb结构:
Below is my mongodb structure:
[{
_id: '111',
items: [{
productId: '123'
}]
}, {
_id: '222',
items: [{
productId: '123'
}, {
productId: '456'
}]
}, {
_id: '333',
items: [{
productId: '123'
}, {
productId: '456'
}, {
productId: '789'
}]
}]
我希望对productId
进行分组和计数,以便结果为:
And I expect to group and count productId
so that the result to be:
[{
productId: '123',
count: 3
}, {
productId: '456',
count: 2
}, {
productId: '789',
count: 1
}]
好吧,我尝试像这样使用aggregation
,但是我想我错了:
Well, I tried using aggregation
like this, but I think I got it wrong:
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 }
]
任何关于如何进行聚合的帮助都将受到赞赏,请不要假设模型有任何变化.
Any help regarding how to do the aggregation probably is appreciated, and please don't assume any change in the model.
提前谢谢!
推荐答案
您需要 $unwind
分组前的项目数组:
You need to $unwind
items array before grouping :
const aggregatorOpts = [{
$unwind: "$items"
},
{
$group: {
_id: "$items.productId",
count: { $sum: 1 }
}
}
]
Model.aggregate(aggregatorOpts).exec()
给出:
{ "_id" : "789", "count" : 1 }
{ "_id" : "456", "count" : 2 }
{ "_id" : "123", "count" : 3 }
这篇关于猫鼬组和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!