如何用猫鼬对两个字段进行排序?

jro*_*jro 2 database sorting mean mongodb node.js

我试图让用户看到热门帖子。一般的想法是按最近的帖子(_id:-1)排序,然后按最多的投票数(upvotes_count:-1)排序,然后限制结果(.limit(3))。这有点简化,所以请忽略“趋势帖子”的这种实现。

不幸的是,我无法以我想要的方式返回两种类型。因此,对于 6 个帖子的集合,它会返回最近的 3 个帖子,但不会按大多数赞成票对它们进行排序。例如:

帖子 6(赞成:1) 帖子 5(赞成:2) 帖子 4(赞成:1)

我希望它们像这样排序:

帖子 5(赞成:2) 帖子 6(赞成:1) 帖子 4(赞成: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);
     });
Run Code Online (Sandbox Code Playgroud)

没有一个工作。

zan*_*ngw 9

参见sort()定义。

sort({_id: -1, upvotes_count: -1})

意味着_idupvotes_count相同的 _id帖子进行排序,然后按降序排序。不幸的_idObjectId, is 是 12 字节的 BSON 类型,它使用以下方法构造:

  • 一个 4 字节的值,表示自 Unix 纪元以来的秒数,
  • 一个 3 字节的机器标识符,
  • 一个 2 字节的进程 ID,以及
  • 一个 3 字节的计数器,从一个随机值开始。

很难得到相同的ObjectId。即,_id该文档中每条记录的 应该是唯一的。因此,您的测试代码的结果只是按_iddesc排序。

这是一个例子,

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  1      |      5        |
|  4      |      7        |
|  3      |      9        |
|  4      |      8        |
Run Code Online (Sandbox Code Playgroud)

结果sort({_id: -1, upvotes_count: -1})应该是

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  4      |      8        |
|  4      |      7        |
|  3      |      9        |
|  1      |      5        |
Run Code Online (Sandbox Code Playgroud)

upvote_count会进行排序的相同_id

然而,在这种情况下。上有相同_id在这种情况下。

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  1      |      5        |
|  4      |      7        |
|  3      |      9        |
|  2      |      8        |
Run Code Online (Sandbox Code Playgroud)

结果sort({_id: -1, upvotes_count: -1})应该是

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  1      |      5        |
|  2      |      8        |
|  3      |      9        |
|  4      |      7        |
Run Code Online (Sandbox Code Playgroud)