I have 2 collections, Items and Categories, and I'm trying to get a count of how many items are in each category.
An example of what each collection looks like is
Item = [
{
name: "item1",
category: ObjectId("123")
},
{
name: "item2",
category: ObjectId("456")
}, ...]
Category = [
{
_id: ObjectId("123"),
name: "category1"
}, ...]
So far i can count the items of one category using something like this
Item.countDocuments({'category': Category[0].id}).exec(function(err, result) {
console.log(result)
}
>> 1
My question is how can I do this with all my categories? If anyone could help or point me in the right direction would be much appreciated.
The ideal output would be something like this:
{
"category1": 1,
"category2": 3
}
CodePudding user response:
You need to use two aggregation pipelines to achieve result you want.
Item.aggregate([
{
$group: {
_id: "$category", count: { $sum: 1}
}
}
])
In the result _id
will be the id used to group fields which will be category id.
[
{
"_id": ObjectId(123),
"count": 1
},
{
"_id": ObjectId(456),
"count": 1
}
]
Learn more about count aggregation at - https://www.mongodb.com/docs/manual/reference/operator/aggregation/count/