本文介绍了如何按顺序获取最后5个文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我数据库中有 1、2、3、4、5、6、7、8、9、10 (基于timestamp顺序).

Say I have 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 in database (based on timestamp order).

我想依次获得 6、7、8、9、10 .

  MessageModel
    .find()
    .sort({ timestamp: -1 })
    .limit(5)
    .exec()
    .then(messages => console.log(messages))
    .catch(err => console.log(err));

以上方法将给我 10、9、8、7、6 .

我尝试排序两次:

  MessageModel
    .find()
    .sort({ timestamp: -1 })
    .limit(5)
    .sort({ timestamp: 1 })
    .exec()
    .then(messages => console.log(messages))
    .catch(err => console.log(err));

但这会给我 1、2、3、4、5 .

猫鼬有办法按顺序获取最后5个文档吗?

Does Mongoose have a way to get last 5 docs in sequential order?

推荐答案

要满足您的要求,您可以使用聚合查询

To achieve your requirement you can use aggregate query

MessageModel.aggregate([
   { $sort : { timestamp: -1} },
   { $limit : 5 },
   { $sort : { timestamp: 1} }
])
.exec();

这篇关于如何按顺序获取最后5个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:07