Answer the question
In order to leave comments, you need to log in
How to count the number of products in a category in mondodb?
I'm trying to master `mongodb` using the example of an online store
There are 2 collections:
- a list of categories
- a list of products
The product has a `category` field that stores the `_id` of the category to which it belongs
For example:
{ name: 'Product name'; 'category': ObjectId("5b6d68b787364230a4c353e2") }
Answer the question
In order to leave comments, you need to log in
It turned out to be just
db.XX.aggregate( [ {$project: {_id:0, name:1}},
{$group: {_id: "$name", total:{$sum:1} } }
])
on grouping add +1 for each name :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question