Mongoose如何按category分组汇总views统计最受欢迎商品分类
实现按商品分类汇总浏览量的方案
你可以直接使用Mongoose的聚合管道(Aggregation Pipeline)完成分组统计需求,具体实现如下:
首先基于你提供的Schema创建数据模型:
const Product = mongoose.model('Product', ProductsSchema);
然后执行聚合查询:
Product.aggregate([ // 可选:如果需要只统计有浏览记录的商品,可添加此过滤阶段 { $match: { views: { $gt: 0 } } }, // 按商品分类分组,统计每个分类的总浏览量 { $group: { _id: "$productCategory", // 指定分组的依据为productCategory字段 totalViews: { $sum: "$views" }, // 累加当前分组下所有商品的views值 productAmount: { $sum: 1 } // 可选字段:统计当前分类下的商品总数 } }, // 按总浏览量降序排序,最受欢迎的分类排在最前 { $sort: { totalViews: -1 } }, // 可选:格式化返回字段,把_id替换为更易读的分类名字段 { $project: { _id: 0, categoryName: "$_id", totalViews: 1, productAmount: 1 } } ]) .then(res => { // 返回的res即为按受欢迎程度排序的分类统计列表 console.log(res) }) .catch(err => { console.error('统计出错:', err) })
返回结果说明
如果使用了上面的可选$project阶段,返回结果格式示例如下:
[ { categoryName: '数码3C', totalViews: 28941, productAmount: 123 }, { categoryName: '服饰箱包', totalViews: 19234, productAmount: 342 }, // ... 其他分类 ]
内容的提问来源于stack exchange,提问作者Jedi Schmedi
相关产品推荐
相关产品推荐

