Mongodb获得按对象分组的前5名



我正在使用MERN堆栈,需要按模式的某些属性分组,因此例如:这是我的模式,

const likeSchema = new mongoose.Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
commentId: {
type: Schema.Types.ObjectId,
ref: 'Comment'
},
questionId: {
type: Schema.Types.ObjectId,
ref: 'Question'
}
}, { timestamps: true })

现在,我想按questionId分组,然后返回计数最高的5个组。所以本质上,我想要得到最多赞的前5个帖子。有办法做到这一点与mongodb?

任何帮助都是感激的!

您可以先按questionId进行分组,然后对结果进行排序,选择前5条记录

db.collection.aggregate([{
"$group": {
_id: "$questionId",
userId: {
$first: "$userId"
},
commentId: {
$first: "$commentId"
},
questionId: {
$first: "$questionId"
},
count: {
$sum: 1
}
},
},
{ $sort: { "count": -1 } },
{ $limit: 5 },
])

最新更新