Mongoose中使用AND运算符做多列排序:按点赞分享评论数排序如何实现
Mongoose实现视频按点赞、分享、评论数排序的方案
方案1:聚合管道查询(无需修改现有Schema)
直接利用MongoDB聚合能力动态计算评论数再排序,适合查询频率不高的场景:
Video.aggregate([ // 新增评论数字段,统计comments数组长度 { $addFields: { commentCount: { $size: "$comments" } } }, // 按优先级排序:点赞降序 > 分享降序 > 评论数降序 { $sort: { like: -1, share: -1, commentCount: -1 } } ]) .then(videos => { // 处理返回的视频列表 }) .catch(err => { // 错误处理 })
如果需要返回评论关联的完整用户信息,可在$sort阶段后追加$lookup阶段关联User集合即可。
方案2:新增冗余字段优化查询性能(高频查询场景推荐)
如果该排序需求为接口高频调用场景,每次聚合计算数组长度会消耗额外性能,可直接在videoSchema中新增评论数冗余字段,新增/删除评论时同步更新字段值,后续直接用普通查询即可完成排序:
- 修改Schema定义:
var videoSchema = new Schema({ title: { type: String, required: true }, video: { type: String, required: true }, like: { type: Number, default: 0 }, share: { type: Number, default: 0 }, comments: [commentSchema], commentCount: { type: Number, default: 0 } // 新增评论数冗余字段 }, { timestamps: true });
- 新增评论时同步更新冗余字段:
// 新增评论时同步累加评论数 Video.findByIdAndUpdate( videoId, { $push: { comments: newComment }, $inc: { commentCount: 1 } }, { new: true } )
删除评论时同理将$inc的commentCount值改为-1即可。
3. 普通查询直接排序:
Video.find() .sort({ like: -1, share: -1, commentCount: -1 }) .then(videos => { // 处理返回结果 })
内容的提问来源于stack exchange,提问作者Sachin Kumar
相关产品推荐
相关产品推荐

