我试图让用户看到热门帖子。一般的想法是按最近的帖子排序(_id:-1),然后按最多的投票排序(upvotes_count:-1),然后限制结果(.limit(3))。这有点简化,所以请忽略“热门帖子”的这种实现。
不幸的是,我不能以我想要的方式返回两个排序。所以对于六个帖子的集合,它返回最近的三个,但它不会按照最多的赞成票对它们进行排序。例如:
第6篇(upvotes:1)第5篇(upvotes:2)第4篇(upvotes:1)
我希望它们像这样排序:
第5篇(upvotes:2)第6篇(upvotes:1)第4篇(upvotes:1)
我不太感兴趣的关系会发生什么,但至少,我希望有更多的上升职位被列为高于那些较少的上升。
当然,我可以写一个方法来排序这些,但肯定有一种方法可以用MongoDB来做到这一点。
下面是我尝试实现这种排序的一些方法。
// 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);
});
字符串
没有一个奏效。
3条答案
按热度按时间vpfxa7rd1#
参见
sort()
定义。sort({_id: -1, upvotes_count: -1})
个意思是先对
_id
进行排序,然后只对相同的_id
文章按desc顺序对upvotes_count
进行排序。不幸的是,_id
是ObjectId
,这是12字节的BSON类型,构造如下:很难得到相同的
ObjectId
。也就是说,每个记录的_id
在这个文档中应该是唯一的。因此,您的测试代码的结果只是按_id
desc排序。这里有一个例子,
字符串
sort({_id: -1, upvotes_count: -1})
的结果应该是型
upvote_count
将被排序为相同的_id
。然而,在这种情况下。在这种情况下没有相同的
_id
。型
sort({_id: -1, upvotes_count: -1})
的结果应该是型
s71maibg2#
你可以找到大多数投票的文件在某些时候
在过去24小时内投票最多
字符串
gkl3eglg3#
字符串