You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mongoose按rating.rate总和排序获取MongoDB热门商品?

MongoDB按评分总和排序获取热门商品

给定的Mongoose Schema包含嵌套的rating数组,每个元素带有rate字段,要按所有评分的总和排序商品,可通过MongoDB的聚合管道实现:

核心思路

使用聚合管道的$addFields计算每个商品的评分总和,再用$sort按该总和降序排列(分数越高越靠前)。

代码实现

1. Mongoose聚合查询

// 假设你的商品模型名为Product
Product.aggregate([
  // 新增totalRating字段,计算rating数组中rate的总和
  {
    $addFields: {
      totalRating: { $sum: "$rating.rate" }
    }
  },
  // 按totalRating降序排序,-1表示降序,1表示升序
  {
    $sort: { totalRating: -1 }
  },
  // 可选:限制返回的热门商品数量,比如取前10
  // { $limit: 10 }
])
.then(hotProducts => {
  // 处理查询结果
  console.log("热门商品列表:", hotProducts);
})
.catch(error => {
  console.error("查询失败:", error);
});

2. 原生MongoDB命令

如果直接使用MongoDB shell,命令如下:

db.products.aggregate([
  { $addFields: { totalRating: { $sum: "$rating.rate" } } },
  { $sort: { totalRating: -1 } }
])

额外扩展

如果需要关联商品所属用户的信息(Schema中user字段关联了users集合),可以在聚合管道中添加$lookup:

Product.aggregate([
  { $addFields: { totalRating: { $sum: "$rating.rate" } } },
  { $sort: { totalRating: -1 } },
  // 关联users集合,获取商品发布者信息
  {
    $lookup: {
      from: "users",
      localField: "user",
      foreignField: "_id",
      as: "productOwner"
    }
  },
  // 将productOwner数组展开为单个对象(可选)
  {
    $unwind: {
      path: "$productOwner",
      preserveNullAndEmptyArrays: true // 兼容没有关联用户的商品
    }
  }
])

注意事项

  • 若商品的rating数组为空,$sum会返回0,这类商品会排在最后
  • 可以结合$match先过滤掉不需要的商品(比如下架商品),再进行排序

内容的提问来源于stack exchange,提问作者Ömer Faruk Demirel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:42:21