【问题标题】:MongoDB sort the result after limitMongoDB对限制后的结果进行排序
【发布时间】:2017-09-14 07:34:29
【问题描述】:

有没有办法对从限制返回的文档进行排序? 示例:

//returns 10 documents:
db.users.find()
.sort({last_online_timestamp:-1})
.limit(10) 

//returns 10 another documents
db.users.find()
.sort({last_online_timestamp:-1})
.limit(10)
.sort({messages_count:1}); 

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

【问题讨论】:

  • db.user.find().sort({last_online_timestamp:-1}).limit(10).pretty();
  • db.user.find().sort({last_online_timestamp: -1}).limit(10, callback);
  • 试试这个……..
  • @RïshïKêshKümar 如果您建议解决方案,您应该将其作为完整答案发布,而不是作为评论。
  • @Alexander Tyuryaev :在 find() 查询中不能使用 sort() 两次;之前已解决此问题,例如 stackoverflow.com/a/43250870/174843stackoverflow.com/a/14425636/174843stackoverflow.com/q/8474353/174843。相反,您需要使用 Jeff J 建议的聚合。

标签: mongodb sorting limit


【解决方案1】:

您可以使用聚合,例如

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/

【讨论】:

  • 我认为db.users.find().sort({last_online_timestamp:-1}).limit(10).sort({messages_count:1}) 不会起作用。根据文档,无论您编写它的顺序如何,总是在限制之前应用排序。
  • @demolisher 你是对的 - 语法被接受,但结果不是预期的。我已更新答案以仅包含聚合。谢谢!
  • “聚合”的语法难以阅读。那个更好: db.users.aggregate().sort({"last_online_timestamp":1}).limit(10).sort({"messages_count": 1});
猜你喜欢
  • 1970-01-01
  • 2018-07-18
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
相关资源
最近更新 更多