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'
}]
}]
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
}]
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()
I got:
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.
Thanks in advance!
Mongoose | countDocuments() Function The countDocuments() function is used to count the number of documents that match the filter in a database collection.
Definition. $group. The $group stage separates documents into groups according to a "group key". The output is one document for each unique group key. A group key is often a field, or group of fields.
MongoDB $count AggregationThe MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.
You need to $unwind
items array before grouping :
const aggregatorOpts = [{
$unwind: "$items"
},
{
$group: {
_id: "$items.productId",
count: { $sum: 1 }
}
}
]
Model.aggregate(aggregatorOpts).exec()
which gives :
{ "_id" : "789", "count" : 1 }
{ "_id" : "456", "count" : 2 }
{ "_id" : "123", "count" : 3 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With