【问题标题】:Sort collection by mdate field and get the latest 20 results (LIMIT) in MongoDB?按 mdate 字段对集合进行排序并在 MongoDB 中获取最新的 20 个结果(LIMIT)?
【发布时间】:2015-04-08 20:11:01
【问题描述】:

我有一个名为messages 的集合,我需要按mdate 排序,并且只获取SQL 中的最新20 个结果类型的LIMIT,如何?我正在玩这个但没有成功:

db.getCollection('messages').find({}, {"sort" : ['mdate', 'asc']} );

【问题讨论】:

    标签: mongodb mongodb-query database nosql


    【解决方案1】:

    如果您想要最后 20 个文档,您应该按降序排列 $sort 您的文档,并使用 $limit 运算符仅返回 20 个文档。

    db.messages.find().sort({ 'mdate': -1 }).limit(20)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多