MongoDB在limit之后对结果进行排序。

19 浏览
0 Comments

MongoDB在limit之后对结果进行排序。

有没有一种方法可以对从限制返回的文档进行排序?

示例:

//返回10个文档:

db.users.find()

.sort({last_online_timestamp:-1})

.limit(10)

//返回另外10个文档

db.users.find()

.sort({last_online_timestamp:-1})

.limit(10)

.sort({messages_count:1});

我想要的是获取最后登录的10个用户,然后按照消息计数进行排序。

0
0 Comments

MongoDB对结果进行排序排序后进行限制的问题是由于在使用find().sort().limit()方法时,sort方法始终在limit方法之前应用,无论你以什么顺序书写。解决方法是使用聚合框架,通过多个阶段来排序和限制结果。

以下是解决该问题的方法:

你可以使用聚合框架,例如

db.users.aggregate([
    {"$sort": {"last_online_timestamp":1}},
    {"$limit": 10},
    {"$sort": {"messages_count": 1}}
])

这将经过多个阶段来处理集合中的文档:

1. 根据`last_online_timestamp`字段按升序排序。

2. 限制结果为10个文档。

3. 对这10个文档按`messages_count`字段进行升序排序。

根据实际的`last_online_timestamp`字段值,你可能需要将`{"$sort": {"last_online_timestamp":1}}`更改为`{"$sort": {"last_online_timestamp":-1}}`。

有关Mongo聚合更多信息,请参阅[https://docs.mongodb.com/manual/aggregation/](https://docs.mongodb.com/manual/aggregation/)。

另外,使用`db.users.find().sort({last_online_timestamp:-1}).limit(10).sort({messages_count:1})`的方法不会起作用。根据文档,无论你以什么顺序书写,排序始终在限制之前应用。

你是正确的-语法是被接受的,但结果不符合预期。我已更新答案,只包括聚合方法。谢谢你的指正!

聚合方法的语法可能不易阅读,以下是更好的写法:

db.users.aggregate().sort({"last_online_timestamp":1}).limit(10).sort({"messages_count": 1});

通过以上方法,你可以在MongoDB中对结果进行排序和限制。

0