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

编程入门 行业动态 更新时间:2024-09-25 20:34:58

如何用 mongoose 对两个<a href=https://www.elefans.com/category/jswz/34/1771420.html style=字段进行排序?"/>

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

我正在尝试让用户看到热门帖子。总体思路是按最新帖子排序 (_id: -1),然后按最多赞成票排序 (upvotes_count: -1),然后限制结果 (.limit(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);
     });

没有一个有效。

回答如下:

请参阅

sort()
定义。

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

表示首先对

_id
进行排序,然后仅对那些
相同
upvotes_count 的帖子按降序对
_id
进行排序。不幸的是,
_id
ObjectId
,它是12字节BSON类型,构造使用:

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

很难得到相同的

ObjectId
。即,每个记录的
_id
在本文档中应该是唯一的。因此,您的测试代码的结果只是按
_id
desc 排序。

这是一个例子,

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  1      |      5        |
|  4      |      7        |
|  3      |      9        |
|  4      |      8        |

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

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  4      |      8        |
|  4      |      7        |
|  3      |      9        |
|  1      |      5        |

upvote_count
将按相同的
_id
进行排序。

但是,在这种情况下。在这种情况下也有同样的

_id

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  1      |      5        |
|  4      |      7        |
|  3      |      9        |
|  2      |      8        |

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

+---------+---------------+
| _id     |  upvote_count |
+---------+---------------+
|  1      |      5        |
|  2      |      8        |
|  3      |      9        |
|  4      |      7        |

更多推荐

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

本文发布于:2024-06-16 07:22:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771443.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   如何用   两个   mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!