Jedi Schmedi
Jedi Schmedi

Reputation: 818

Group on category and summarize property in mongoose

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' }
);

Upvotes: 0

Views: 21

Answers (1)

J.F.
J.F.

Reputation: 15187

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

Upvotes: 1

Related Questions