DEV Community

Cover image for get number of product in each category with mongodb aggregate
ma2web
ma2web

Posted on • Edited on

4 2

get number of product in each category with mongodb aggregate

In one project, the Android developer asked me to give me an API that can show product categories with the number of products in each category; the best way to create this API in MongoDB is to use the 'aggregate' operator.
This was my category schema.

const mongoose = require("mongoose");
const { s, rs, n, ref } = require("../utils/mongo");

var schema = new mongoose.Schema(
  {
    user: ref("user"),
    name: { ...rs, unique: true },
    description: s,
    image: s,
    view: {
      ...n,
      default: 0,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("category", schema);
Enter fullscreen mode Exit fullscreen mode

and you can see my controller in below

module.exports = {
  getAll: async (req, res) => {
    await Category.aggregate([
        {
          $lookup: {
            from: "products",
            localField: "_id",
            foreignField: "categories",
            as: "products",
          },
        },
        {
          $project: {
            _id: 1,
            name: 1,
            products: { $size: "$products" },
            description: 1,
            view: 1,
            createdAt: 1,
            updatedAt: 1,
          },
        },
      ]).exec(function (err, result) {
        if (err) throw err;
        res.send(result);
      });
  },
Enter fullscreen mode Exit fullscreen mode

and this is postman result

postman result

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay