I'm trying to allow users to see trending posts. The general idea is to sort by the most recent posts (_id: -1) and then sort those by most upvotes (upvotes_count: -1) and then limiting the results (.limit(3)). This is a bit simplified, so please ignore this implementation of "trending posts".
Unfortunately, I'm not able to return two sorts in the way that I want. So with a collection of six posts, it returns the most recent three, but it doesn't then sort them by most upvotes. For instance:
Post 6 (upvotes: 1) Post 5 (upvotes: 2) Post 4 (upvotes: 1)
I want them to be sorted like so:
Post 5 (upvotes: 2) Post 6 (upvotes: 1) Post 4 (upvotes: 1)
I'm not so interested in what happens with ties, but at a minimum, I want the posts that have more upvotes to be listed higher than those with less upvotes.
Of course, I could write a method to sort these, but surely there is a way to do this with MongoDB.
Below are some of the ways I've tried to implement this sort.
// Use sort for date and then use it again for upvotes_count
Post.find()
.sort({_id: -1})
.sort({upvotes_count: -1})
.limit(3)
.exec( function(err, posts) {
if (err) res.send(err);
console.log(posts);
res.json(posts);
});
// Use sort for date, limit the results to three, and then
// use it again for upvotes_count
Post.find()
.sort({_id: -1})
.limit(3)
.sort({upvotes_count: -1})
.exec( function(err, posts) {
if (err) res.send(err)
console.log(posts);
res.json(posts);
});
// Use sort for date and upvotes_count in one step.
Post.find()
.sort({_id: -1, upvotes_count: -1})
.limit(3)
.exec( function(err, posts) {
if (err) res.send(err);
console.log(posts);
res.json(posts);
});
None have worked.