Reputation: 141
I have 100 user in database Each user have started 5 course. Each course have statistics.
Course example:
{
userId: [email protected],
score: 50
}
database schema:
{
userId: {
type: ObjectId,
ref: Users
},
score: Number
}
Each user have 5 similar document in database, as I mentioned above.
I tried aggregation (group) with date: "$last" command but I didn't get any info.
I want to find top 20 unique user with their latest course result and sorted by score (high score).
Upvotes: 0
Views: 126
Reputation: 2680
as per your schema, aggregate query:
[
{
"$group": {
"_id": "$userId",
"score": {
"$last": "$score"
}
}
}
]
will get you all the unique users(Group By) with last record of score
.
and as you wanted to get only 20 users , we can put a $limit condition:
[
{
"$group": {
"_id": "$userId",
"score": {
"$last": "$score"
}
}
},{
$limit:20
}
]
Upvotes: 1