How to get last 5 docs in sequential order?

后端 未结 2 785
粉色の甜心
粉色の甜心 2021-01-24 08:00

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

I want to get 6, 7, 8, 9, 10 in sequentia

相关标签:
2条回答
  • 2021-01-24 08:26

    To achieve your requirement you can use aggregate query

    MessageModel.aggregate([
       { $sort : { timestamp: -1} },
       { $limit : 5 },
       { $sort : { timestamp: 1} }
    ])
    .exec();
    
    0 讨论(0)
  • 2021-01-24 08:28

    You can use Array#reverse to efficiently reverse the order of the elements in your messages array in place to put them back in ascending order:

    MessageModel
        .find()
        .sort({ timestamp: -1 })
        .limit(5)
        .exec()
        .then(messages => {
            messages.reverse();
            console.log(messages);
        })
        .catch(err => console.log(err));
    
    0 讨论(0)
提交回复
热议问题