Reputation: 7133
I'm creating a quick leaderboard for a game. The leaderboard shows the most recent 10 players sorted by their score. My query doesn't seem to be working:
recordModel.find({ game: gameId }).sort({updatedAt: -1}).limit(10).sort({ score: -1 }).exec( /*... */ );
It only returns most recent 10 records without the seconds sorting.
How can I get the desired result? (Yes I know I can sort the result array by myself, but it doesn't feel "right" for me)
Edit: problem solved, but I cannot accept my own answer in 2 days. I will when the time comes, thank you very much for your time!
Upvotes: 2
Views: 728
Reputation: 7133
In the end I solved the problem using aggregate
:
recordModel.aggregate([ { $match: { game: gameId} }, { $sort : { updatedAt : -1 } }, { $limit : 10 }, { $sort : { score : -1 } } ]).exec(/* ... */)
Upvotes: 0
Reputation: 2743
Can you try with only one "sort", like this ?
recordModel.find({ game: gameId })
.sort({updatedAt: -1, score: -1})
.limit(10)
.exec( /*... */ );
More information here : sorting-priority
Hope it helps.
Upvotes: 2