Hongbo Miao
Hongbo Miao

Reputation: 49954

How to get last 5 docs in sequential order?

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 sequential order.

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

The above method will give me 10, 9, 8, 7, 6.

I tried to sort twice:

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

But this will give me 1, 2, 3, 4, 5.

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

Upvotes: 1

Views: 221

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 312095

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));

Upvotes: 1

Shaishab Roy
Shaishab Roy

Reputation: 16805

To achieve your requirement you can use aggregate query

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

Upvotes: 1

Related Questions