The following 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'
}]
}]
And I expect to group and assume productIdthat the result is:
[{
productId: '123',
count: 3
}, {
productId: '456',
count: 2
}, {
productId: '789',
count: 1
}]
Well, I tried using aggregationlike this, but I think I was wrong:
const aggregatorOpts = [{
$group: {
_id: "$items.productId",
count: { $sum: 1 }
}
}]
Model.aggregate(aggregatorOpts).exec()
I got:
result [
{ _id: [ '123' ], count: 1 },
{ _id: [ '123', '456' ], count: 1 },
{ _id: [ '123', '456', '789' ], count: 1 }
]
Any help regarding how to do aggregation is likely to be appreciated, and please do not accept any changes to the model.
Thanks in advance!