DEV Community

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

Posted on • Updated on

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

Top comments (0)