Home > Software design >  Group on category and summarize property in mongoose
Group on category and summarize property in mongoose

Time:11-05

I got a schema for products. Each time a user looks at a product I increase the "views" property by one. Now I want to list the most popular category. How can I group on category an summarize the views on all products in same category?

const ProductsSchema = new mongoose.Schema(
  {
    programId: {
      type: Number,
    },
    
    productName: {
      type: String,
    },
    productPrice: {
      type: Number,
    },
    productCategory: {
      type: String,
    },
    views: {
      type: Number,
    },
  },
  { collection: 'products' }
);

CodePudding user response:

If I've understood correctly simply $group by $productCategory and $sum the number of views.

yourModel.aggregate([
  {
    "$group": {
      "_id": "$productCategory",
      "views": {
        "$sum": "$views"
      }
    }
  },
  {
    "$sort": {
      "views": -1
    }
  }
])

Example here.

Also you can $limit to get only the top value: example

  • Related