niranjay_30
niranjay_30

Reputation: 35

Get number of products from each category in mongodb database

I'm new to mongodb and to overall databases side of development.

I'm trying to make a product listing site where all the categories would be displayed with the number of products within that particular category and when clicked on a particular category, it would get me all the products in that category.

Some things to note are:

I don't know how to go about this problem and tried searching it online but couldn't exactly find what I was looking for. I've also tried making the schema for this but I do not know if it's the right approach or not and this is how it looks:

const productsSchema = {
    category: String,
    name: String,
    price: String,
    description: String,
    thumbnail: String,
};

Side note: I'm using MERN stack.(if its of any help)

Upvotes: 1

Views: 2038

Answers (2)

J.F.
J.F.

Reputation: 15215

If I've understand well your question, you can use something like this:

db.collection.aggregate([
  {
    "$match": {
      "category": "category1"
    }
  },
  {
    "$count": "total"
  }
])

With this query you will get the total $count for each category. Example here

In your frontend you will need a call for every category.

Maybe if your DB has a lot of different categories this is not a good approach, but if the number is not large enough you can call this query a couple times and you will get the result you want.

MongoDB Documentation reference here

Upvotes: 1

Pablo Gonzalez
Pablo Gonzalez

Reputation: 1810

I would say you should have a product schema and a product category schema, where the product category schema has an array of product ids that belong to that category.

In the product schema, you could also have a pointer to the category object that a product is linked to (as opposed to just the name of the category as a string).

Maybe take a look at mongoose populate https://mongoosejs.com/docs/populate.html

Upvotes: 0

Related Questions