MongoDB 对限制后的结果进行排序

标签 mongodb sorting limit

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

//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.users.aggregate([
    {"$sort": {"last_online_timestamp":1}},
    {"$limit": 10},
    {"$sort": {"messages_count": 1}}
])

这将经历集合中文档的阶段:

  1. last_online_timestamp字段升序排序
  2. 限于 10 个文档
  3. 这 10 个文档将按 messages_count 字段升序排序

您可能希望将 {"$sort": {"last_online_timestamp":1} 更改为 {"$sort": {"last_online_timestamp":-1}取决于 last_online_timestamp

的实际值

有关 Mongo 聚合的更多信息,请参阅 https://docs.mongodb.com/manual/aggregation/ .

关于MongoDB 对限制后的结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43472561/

相关文章:

mongodb - 无法解析行 #126 : mongo. 数据库 = mongo_db_test

sorting - 有没有类似 memcached 的东西,但用于排序列表?

c# - Asp.NET 4.0 GridView 默认排序方向和表达式

php - 如何对多个用户插入不同位置的列表进行排序/排序?

c++ - std::basic_string<_CharT> 字符串的最大长度

python - QDial 禁用完整游览

python - json.encoder.FLOAT_REPR 已更改但没有效果

Mongodb 数组 $push 和 $pull

MongoDB 插入音频

javascript - 过滤子文档数组,同时如果为空仍返回父数据