这就是我的猫鼬模式的样子:
const QuizModel = new mongoose.Schema({
quizId: { type: String, required: true, trim: true },
userId: { type: String, required: true, trim: true },
result: {
score: { type: Number, required: true},
time: { type: Number, required: true },
},
});
这是一个测验应用程序,因此有多个文档具有相同的userId
。
我试图进行查询以建立排行榜,而我想到了这一点。
const topUsers = await QuizModel.find({})
.sort({ "result.score": "desc", "result.time": "asc" })
.limit(10);
现在,由于我只想显示前10位用户,因此我添加了.limit(10)
。
现在,在这10个文档中,所有10个文档都有相同的用户,即相同的userId
。
如何防止出现这种情况,并仍然获得10个具有唯一的userId
的文档?
我不希望一个用户占据排行榜中的所有10个位置。
示例: User1 有5个具有上述架构的文档,其得分分别为100、95、92、90、60 User2 有5个具有上述架构的文档,得分分别为95、92、90、80、60
预期输出为:
[
{
quizId: "....",
userId: "user1",
result: {
score: 100,
time: "some_time"
}
},
{
quizId: "....",
userId: "user2",
result: {
score: 95,
time: "some_time"
}
}
]