V
V
Viktor Novikov2018-08-18 19:52:47
JavaScript
Viktor Novikov, 2018-08-18 19:52:47

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") }

The simplest thing that came to my mind was to have a `productsCount` field in the categories, which will be updated when products are inserted/removed. But this is IMHO tin.
Actually, the question is: how to calculate the number of goods in a category and not "put a server" and not make crutches?
Or Monga is not suitable for such tasks?
Or am I solving it crookedly?
----
...give markdown to the toaster!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
adm666, 2018-08-24
@YourDesire

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 :)

E
Egor, 2018-08-19
@DarkSir

db.products.count( { category: { $gt: ObjectId("5b6d68b787364230a4c353e2") } } )

Maybe it will help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question