如何用Mongoose获取played_frequency最高的前10条文档?
获取Mongoose模型中played_frequency最高的前10条文档
要实现这个需求,只需对played_frequency字段做降序排序,再限制返回结果数量为10即可,以下是具体实现代码:
1. 确认Mongoose模型定义(基于ITrack接口)
import mongoose, { Model, Schema } from 'mongoose'; export interface ITrack { genre: string; title: string; artist: string; featuring?: string; duration: string; coverImage?: string; image: string; url: string; trending?: number; played_frequency: number; promoted?: boolean; likes?: number; } const trackSchema = new Schema<ITrack>({ genre: { type: String, required: true }, title: { type: String, required: true }, artist: { type: String, required: true }, featuring: String, duration: { type: String, required: true }, coverImage: String, image: { type: String, required: true }, url: { type: String, required: true }, trending: Number, played_frequency: { type: Number, required: true }, promoted: Boolean, likes: Number }); const Track: Model<ITrack> = mongoose.model<ITrack>('Track', trackSchema);
2. 编写查询函数
async function getTop10MostPlayedTracks() { try { // 按played_frequency降序排序,取前10条 const topTracks = await Track.find() .sort({ played_frequency: -1 }) // -1代表降序,1代表升序 .limit(10); // 限制返回结果数量为10 return topTracks; } catch (error) { console.error('查询失败:', error); throw error; } } // 调用示例 getTop10MostPlayedTracks() .then(tracks => console.log('播放量Top10曲目:', tracks)) .catch(err => console.error(err));
补充说明
- 如果需要排除某些不需要的字段,可以在
find()后添加.select()方法,比如.select('-_id -__v')表示不返回_id和__v字段 - 若要只返回特定字段,可写为
.select('title artist played_frequency') - 确保
played_frequency字段在Schema中定义为Number类型,否则排序可能出现异常
内容的提问来源于stack exchange,提问作者user3118363
相关产品推荐
相关产品推荐

